2017-03-31 75 views
0

我能夠添加到本地存儲和刪除項目,但它不會顯示添加項目在我的HTML。一旦某項內容被添加到本地存儲中,它應該顯示在「收藏夾」頁面上,然後在刪除時應從收藏夾頁面中刪除。這是代碼的查看收藏夾部分,似乎沒有工作。在頁面顯示本地存儲:jquery

//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

在控制檯中的任何錯誤? 'object'裏面有什麼嗎?在元素呈現後('$(document).ready()')獲取觸發的函數'displayPageContent'?這些元素是否都存在? – empiric

+0

它在一個數組內 –

+0

每次向localStorage添加或刪除對象時,是否再次調用顯示函數,即「displayPageContent()'?我認爲你只在頁面加載時才調用它。每當localStorage中的數據發生更改時,都需要調用它,以便它可以顯示最新的數據。 –

回答

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')); 
 
});

相關問題