丢失会话存储数据

时间:2015-09-28 05:47:55

标签: jquery sessionstorage

我正在尝试将表中的specSizespecTitlespecURL存储到会话存储中,并将在不同的页面中使用它。在加载时我看到会话数据,但如果我尝试通过单击按钮将项目添加到会话存储,它会清除现有项目并放入新项目,而不是将onclick项目附加到现有项目。

这是我的代码:

 window.specSize;
 window.specTitle;
 window.specURL;

 function specInfo (sSize, sTitle, sURL){
  this.specSize = sSize;
  this.specTitle = sTitle;
  this.specURL = sURL;
 }
 var specArr = []
 $('.flag-bookmarks a').on("click",function(e){
    e.preventDefault();
    specSize = $(this).parent().parent().parent().find("td:first").html();
    specTitle = $(this).parent().parent().parent().find("td:nth-child(2) a").html();
    specURL=$(this).parent().parent().parent().find("td:nth-child(2) a").attr("href");
    specArr.push(new specInfo(specSize,specTitle,specURL))
    sessionStorage.setItem('storedInfo', JSON.stringify(specArr));
 });
  storedValue = JSON.parse(sessionStorage.getItem('storedInfo'));
  alert(storedValue);

1 个答案:

答案 0 :(得分:2)

问题是会话存储只支持数据类型为" String"用于存储。因此,在设置之前需要JSON.stringify您的对象,并且JSON.parse它用于获取会话存储对象。

参考:How do I store an array in localStorage?

所以你必须做以下

  1. 使用JSON.parse(sessionStorage.getItem('storedInfo'));
  2. 从变量中获取会话存储中的项目
  3. 将新项目附加到上述变量
  4. 使用JSON.stringify();
  5. 设置会话存储空间

    由于您在设置之前已经进行了字符串化,因此您必须执行第一步和第二步。

    希望这有帮助