2015-09-28 102 views
1

我想存儲specSize,specTitlespecURL它們在表中的會話存儲,將在不同的頁面中使用它。在負載上,我看到會話數據,但如果我嘗試通過單擊按鈕將項目添加到會話存儲,它將清除現有項目並放入新項目,而不是將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); 

回答

2

的問題是會話存儲僅支持數據類型爲「字符串」存儲。所以你需要JSON.stringify你的對象設置和JSON.parse它獲取會話存儲對象。

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

所以,你必須做到以下幾點

  1. 使用JSON.parse(sessionStorage.getItem('storedInfo'));
  2. 追加新項目,以上述變量
  3. 套裝獲取從會話存儲在一個變量的項目會話存儲使用JSON.stringify();

由於您在設置之前已經進行了字符串化,因此您必須執行第一步和第二步。

希望這會有所幫助