2017-08-31 57 views
0

我的問題有兩個方面,很適合獲得另一個視角。本地存儲在刷新後不會持續

我正在保存一些數據到localStorage,但是如果我刷新數據就沒了。另一個問題是,只有最後一次點擊的項目纔會被添加到localStorage。任何幫助都會很棒。

function getItem(callback){ 
 
    var itemsObj; 
 
    $('.info').on('click', function(){ 
 
    itemsObj = {}; 
 
    $this = $(this); 
 
    itemsObj.gameImg = $this.parent().parent().find('img').attr('src'); 
 
    itemsObj.gameTitle = $this.parent().parent().find('h2').text(); 
 
    itemsObj.gameInfo = $this.parent().parent().find('p').text(); 
 
    // call the callback function parameter and send itemsObj as argument, callback function then received the argument as you wanted it to be. Then execute stuff from there. 
 
    callback(itemsObj); 
 
    }); 
 
} 
 

 
// send a function instead for getItem to call when all is well 
 
getItem(function (data) { 
 
    // here you will receive the data 
 
    console.log('from function:', data); 
 
    localStorage.data = (JSON.stringify(data)); 
 
    if(localStorage.getItem("data")){ 
 
    var savedLocal = localStorage.getItem("data"); 
 
    savedLocal = JSON.parse(savedLocal); 
 
    var favsResult = $('.favs-display-data'); 
 
    favsOutput = `<div class="col-lg-3 game"> 
 
        <div class="view view-first"> 
 
        <img src="${savedLocal.gameImg}"/> 
 
        <div class="mask"> 
 
         <h2>${savedLocal.gameTitle}</h2> 
 
         <p>${savedLocal.gameInfo}</p> 
 
         <a href="#" class="info">♥</a> 
 
        </div> 
 
        </div> 
 
       </div>` 
 
    favsResult.append(favsOutput); 
 
    } 
 
    console.log('savedLocal: ', savedLocal);

回答

1

你有你需要使用localStorage.setItem("KEY-NAME", "VALUE");

不使用localStorage.data的問題......那是錯的

1

這可能有助於爲您提供:

localStorage.setItem("variable_name","value"); 
localStorage.getItem("variable_name"); 

但是,如果你是斯托裏NG JSON那麼你需要通過設置localStorage的:

localStorage.setItem("variable_name",JSON.stingify("value")); 

而且從localStorage的再獲取數據的時間,

var data=JSON.parse(localStorage.getItem("variable_name")); 
0
<html> 
<head> 
<script type="text/javascript"> 
function persistData() { 
    localStorage.setItem('key', 'val'); 
} 
localStorage.getItem('key'); 
</script> 
</head> 
<body> 
<button type="button" onclick="persistData()">Store</button> 
</body> 
</html> 

在其瀏覽器中,你所面臨的問題,因爲大多數情況下它直接運行。 只有在使用前需要進行stringyfy或parse。