我正在尝试将表中的specSize
,specTitle
和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);
答案 0 :(得分:2)
问题是会话存储只支持数据类型为" String"用于存储。因此,在设置之前需要JSON.stringify
您的对象,并且JSON.parse
它用于获取会话存储对象。
参考:How do I store an array in localStorage?
所以你必须做以下
JSON.parse(sessionStorage.getItem('storedInfo'));
JSON.stringify();
由于您在设置之前已经进行了字符串化,因此您必须执行第一步和第二步。
希望这有帮助