我可以添加到本地存储并删除项目,但它不会在我的html中显示添加的项目。将某些内容添加到本地存储后,它应显示在“收藏夹”页面上,然后在删除时应将其从“收藏夹”页面中删除。它是代码的收藏部分,似乎无法正常工作。
//Add Favorites
$('.favoritesbtn').click(function() {
var storedbar = JSON.parse(localStorage.getItem('storedBar'));
var favArray = [];
favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
localStorage.setItem('favorites', JSON.stringify(favArray));
console.log(localStorage.getItem('favorites'));
});
//viewing favorites
var favBar = JSON.parse(localStorage.getItem('favorites'));
console.log(favBar);
function displayPageContent(object) {
if (object) {
$('#bar-info h2').html(object.barname);
$('#bar-info h5').html(object.address);
$('#bar-info p').html(object.description);
$('#bar-info img').html(object.image);
}
}
displayPageContent(favBar);
//Removing favorites
$('.removebtn').click(function() {
console.log('delete');
localStorage.removeItem('favorites');
console.log(localStorage.getItem('favorites'));
});

答案 0 :(得分:0)
每次更改“收藏夹”时,您都需要致电displayPageContent(localStorage.getItem('favorites'));
。
我没有像html这样的其他代码,如果这不起作用,请发布您的其他代码。并确保检查您的控制台日志以确保数据正确。
//Add Favorites
$('.favoritesbtn').click(function() {
var storedbar = JSON.parse(localStorage.getItem('storedBar'));
var favArray = [];
favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
localStorage.setItem('favorites', JSON.stringify(favArray));
console.log(localStorage.getItem('favorites'));
//update view
displayPageContent(localStorage.getItem('favorites'));
});
//viewing favorites
var favBar = JSON.parse(localStorage.getItem('favorites'));
console.log(favBar);
function displayPageContent(object) {
if (object) {
$('#bar-info h2').html(object.barname);
$('#bar-info h5').html(object.address);
$('#bar-info p').html(object.description);
$('#bar-info img').html(object.image);
}
}
displayPageContent(favBar);
//Removing favorites
$('.removebtn').click(function() {
console.log('delete');
localStorage.removeItem('favorites');
console.log(localStorage.getItem('favorites'));
//update view
displayPageContent(localStorage.getItem('favorites'));
});