我正在尝试将表中的specSize
、specTitle
和specURL
存储到 session 存储中,将在不同的页面中使用它。加载时我会看到 session 数据,但如果我尝试通过单击按钮将项目添加到 session 存储中,它将清除现有项目并放置新项目,而不是将 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);
最佳答案
问题是 session 存储仅支持“String”数据类型进行存储。所以你需要JSON.stringify
设置之前的对象和 JSON.parse
它用于获取 session 存储对象。
引用:How do I store an array in localStorage?
所以你必须执行以下操作
- 使用
JSON.parse(sessionStorage.getItem('storedInfo'));
从变量中的 session 存储中获取项目 - 将新项目附加到上述变量
- 使用
JSON.stringify();
设置 session 存储
由于您在设置之前已经进行了字符串化,因此您必须执行第一步和第二步。
希望这有帮助
关于jquery - 丢失 session 存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816398/