sessionStorage不能使用JSON.stringify或?

时间:2017-06-02 14:29:42

标签: javascript

为什么这不起作用?

function VarsStorage(act,varname,val){
  if(act == 'get'){
    return sessionStorage.getItem(varname+'Cache');
  }else if(act == 'set'){
    sessionStorage.setItem(varname+'Cache', val);   
  }
}

VarsStorage('set','addStocksList',JSON.stringify(holder));

我尝试了这段代码的许多组合,但它仍然无效。

2 个答案:

答案 0 :(得分:0)

设置适合我:

$scope.example = function($event){
    var target = $($event.target);
    $(target).css("background-color", "white");
    $(target).css("border-color", "red");
};

但是如果从存储中获取序列化对象,则必须使用var holder = { ... }; VarsStorage('set','addStocksList',JSON.stringify(holder)); 将字符串解析为对象:

JSON.parse

答案 1 :(得分:0)

这里工作正常,只需设置holder

即可
function VarsStorage(act,varname,val){
  if(act == 'get'){
    return sessionStorage.getItem(varname+'Cache');
  }else if(act == 'set'){
    sessionStorage.setItem(varname+'Cache', val);   
  }
}

var holder = { "name":"John", "age":30, "city":"New York"};
VarsStorage('set','addStocksList',JSON.stringify(holder));

VarsStorage('get','addStocksList');
//return
//"{"name":"John","age":30,"city":"New York"}"