在getItem,setItem

时间:2016-12-09 01:48:48

标签: javascript jquery local-storage

我正在尝试使用jQuery在localStorage中保存数据。每次刷新Chrome浏览器时,我尝试保存的数据都会重置。首先,我通过getItem从字典中检索数据,然后使用setItem进行设置。听起来很简单,但我无法保存。任何帮助表示赞赏。感谢

这是我的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)

2 个答案:

答案 0 :(得分:1)

您替换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) ,因为每个子对象具有相同的属性,因此无论如何它都会替换。改变是这样的。

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) 中每个对象的状态。

Include

答案 1 :(得分: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!