我试图创建一个删除按钮来从表中删除项目行,但我不断遇到"Uncaught TypeError: deletedArr。Push不是一个函数。我不知道该怎么办。下面是代码:
//Remove buttom
$(document).ready(function() {
// As soon as jquery loads, load from storage
// it will return null if nothing is stored yet
const deletedExpenses = JSON.parse(localStorage.getItem('deletedExpenses')) || [];
$('body').on('click', '.deleteButton', function(e) {
e.preventDefault(); // prevent the href default
// if you need to access the id...
let deleteID = $(this).data('id');
$(this).closest('tr').remove();
// You first have to load from storage the array of deleted items,
var deletedArr = localStorage.getItem("deletedExpenses");
// If you have nothing stored, this will return null,
// And if that's the case, create new array
if (!deletedArr){
deletedArr = [];
}
// then push to this array another ID that got deleted
deletedArr.push(deleteID);
localStorage.setItem('deletedExpenses', JSON.stringify(deletedArr));
})
将变量设置为字符串:
var deletedArr = localStorage.getItem("deletedExpenses");
当您设置本地存储值时,您将其编码为JSON,因此您需要在读取 JSON时将其解析回:
var deletedArr = JSON.parse(localStorage.getItem("deletedExpenses"));