2017-08-31 7 views
0

私の質問は2倍で、別の見解を得るのはいいと思います。ローカルストレージはリフレッシュ後も維持されません

私はいくつかのデータをlocalStorageに保存していますが、データを更新するとそのデータはなくなります。もう1つの質問は、最後にクリックされたアイテムだけが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"); 

しかし、もしあなたがストーリーならあなたが問題に直面している

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> 

どのブラウザ上にあるため、

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

その後のlocalStorageからデータをフェッチする際の:あなたはでのlocalStorageを設定する必要がNGのJSONほとんどがまっすぐに走っています。 使用する前にstringyfyまたは解析する必要があります。

関連する問題