2016-12-09 4 views
0

jQueryを使用してlocalStorageにデータを保存しようとしています。保存しようとしているデータは、Chromeブラウザをリフレッシュするたびにリセットされます。まず、辞書からgetItemまでデータを取得してから、setItemを使用してデータを設定します。かなりシンプルな音が、私はそれを保存することはできません。どんな助けもありがとうございます。おかげgetItem、setItemの後にChromeでlocalStorageがリセットされる

は、ここに私のJSです:

moneylove = {"snacks":{"c":1,"m":1,"e":2},"food":{"c":2,"m":0,"e":1},"soap":{"c":2,"m":0,"e":0},"toys":{"c":2,"m":1,"e":2}} //dog state 
for (state in moneylove["snacks"]){ 
    stateadd = JSON.parse(localStorage.getItem(state)) 
    stateadd += moneylove["snacks"][state] 
    localStorage.setItem(state,JSON.stringify(stateadd)) 
} 
console.log(localStorage) 
+1

Questionで 'javascript'の前に' localStorage'を設定していますか? – guest271314

+0

ブラウザデベロッパーツールはsetItemの後にローカルストレージデータを表示していますか? – rogeriolino

答えて

1

それはとにかく置き換わるように、各サブオブジェクトは、同じ性質を持っているので、あなたがkey Sを交換してください。このように変更してください。

var moneylove = {"snacks":{"c":1,"m":1,"e":2},"food":{"c":2,"m":0,"e":1},"soap":{"c":2,"m":0,"e":0},"toys":{"c":2,"m":1,"e":2}} //dog state 
for (state in moneylove["snacks"]){ 
    stateadd = JSON.parse(localStorage.getItem(state)) 
    stateadd += moneylove["snacks"][state] 
    localStorage.setItem("snacks" + state,JSON.stringify(stateadd)) // Make key be unique. 
} 
console.log(localStorage) 

EDIT

例を以下のように、完全な計算及び記憶方法。これにより、各オブジェクトの状態をmoneyloveに計算できます。

var moneylove = {"snacks":{"c":1,"m":1,"e":2},"food":{"c":2,"m":0,"e":1},"soap":{"c":2,"m":0,"e":0},"toys":{"c":2,"m":1,"e":2}} //dog state 

for(var itemKey in moneylove) { 
    var item = moneylove[itemKey]; 
    for (var stateKey in item){ 
    var storageKey = itemKey + "-" + stateKey; 
    var stateadd = JSON.parse(localStorage.getItem(storageKey) || '0') 
    stateadd += item[stateKey]; 
    localStorage.setItem(storageKey, JSON.stringify(stateadd)) // Make key be unique. 
    } 
} 
console.log(localStorage) 
1

var DB = function(){ 
    this.Read = function(index){ 
     return JSON.parse(localStorage[index]).data; 
    }; 

    this.Write = function(index, data){ 
     localStorage[index] = JSON.stringify({data : data}); 
    }; 

    this.Test = function(){ // test support localStorage! 
     return typeof localStorage == typeof {}; 
    }; 

    this.Clear = function(index){ 
     if(typeof index === "undefined"){ 
     localStorage = {}; 
     } else { 
     localStorage[index] = JSON.stringify({data : []}); 
     } 
    }; 
} 

// example: 
var x = new DB(); // new data base 
if(!x.Test()) alert('Error!'); // not support! 
x.Write('food', ['food','bar','google']); // write data 
console.log(x.Read('food')); // get data! 

x.Clear('food'); // clear data! 
console.log(x.Read('food')); // get data! 
関連する問題