2

我正在尝试存储specSizespecTitle并且specURL在会话存储的表中,将在不同的页面中使用它。在加载时,我会看到会话数据,但如果我尝试通过单击按钮将项目添加到会话存储中,它会清除现有项目并放置新项目,而不是将 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);
4

1 回答 1

2

问题是会话存储仅支持数据类型为“字符串”进行存储。所以你需要JSON.stringify在设置之前你的对象和JSON.parse它来获取会话存储对象。

参考:如何在 localStorage 中存储数组?

因此,您必须执行以下操作

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

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

希望这可以帮助

于 2015-09-28T06:39:09.457 回答