2015-04-24 135 views
3

我試圖顯示已存儲在本地存儲中的數組中的值。我已經能夠將值存儲在本地存儲中,並在點擊按鈕時添加其他值,但我無法將值重新取出並顯示在頁面上。從本地存儲顯示數組值

這是我的代碼,它增加了本地存儲的值。

$("#player1Link").click(function() { 

      if (localStorage.getItem("player1Favourite") !== null) { 
       var a = JSON.parse(localStorage.getItem('player1Favourite')); 
       if (a.indexOf(chosenPlayerId) === -1) { 
        a.push(chosenPlayerId); 
        localStorage.setItem('player1Favourite', JSON.stringify(a)); 
        alert("Pushed in"); 
       } else { 
        alert("Already in favourites"); 
       } 
      } else { 
       var a = []; 
       a.push(chosenPlayerId); 
       localStorage.setItem('player1Favourite', JSON.stringify(a)); 
      } 
     }) 

我希望能夠點擊一個按鈕來檢索值,並在頁面上顯示出來,但我可以找出代碼在此功能中去。 $("#playerRetrieve").click(function() {}); 如果有人能幫助它,將不勝感激。

回答

2

我做了一個的jsfiddle,似乎在那裏工作:jsfiddle

嘗試:

localStorage.getItem('player1Favourite'); 

或:

localStorage.player1Favourite 

你可能想看看: this topic 或在 Mozilla

1

我不完全確定自己正確理解你,因爲如果你只是想要檢索值,你可以使用相同的代碼,只需從代碼中刪除插入並更改jQuery選擇器。

$("#playerRetrieve").click(function() { 
    if (localStorage.getItem("player1Favourite") !== null) { 
     var a = JSON.parse(localStorage.getItem('player1Favourite')); 
     // Do what you want with the values, which are now in a. 
    } 
});