【问题标题】:Losing session storage data丢失会话存储数据
【发布时间】:2016-05-26 15:00:10
【问题描述】:

我正在尝试将表中的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);

【问题讨论】:

    标签: jquery sessionstorage


    【解决方案1】:

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

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

    所以你必须做以下事情

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

    由于你在设置之前已经进行了字符串化,所以你必须进行第一步和第二步。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 2018-01-27
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多