我已经添加了一个删除函数,它正在成功地删除行,但我想从JavaScript中删除本地存储



我添加了一个删除函数,它成功地删除了行,但我想在JavaScript中从localstorage中删除当用户重新加载页面时,它也可以从本地存储中删除,这样书就不会出现了当函数点击时,我想从本地存储中删除它,就是它

JavaScript文件

class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow()"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}

function RemoveRow(uid) {
// event.target will be the input element.
let td1 = event.target.parentNode; 
let tr1 = td1.parentNode; 
tr1.parentNode.removeChild(tr1);// the row to be removed
window.localStorage.setItem("books", JSON.stringify(books));
}
$('tableBody').on('click', 'input[type="button"]', function(e){
$(this).closest('tr').remove()
})

HTML文件

<div id="table">
<h1>Your Books</h1>
<table class="table table-dark table-striped">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Author</th>
<th scope="col">Type</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody class="tableBody" id="tableBody"> </tbody>
</table>
</div>
</div>

在我看来,我想当你根据id过滤书籍,然后再次将它们设置到本地存储时,就会解决你的问题。

const newBooks= books.filter(book=> book.id !== idThatYouNeedToDelete)

localStorage.setItem("books"JSON.stringify (newBooks));

最新更新