2016-08-01 39 views
0

我試圖將多個值(標題)存儲到單個密鑰中。我提示用戶首先輸入他們的標題,然後將其保存爲「標題」。但是,當我輸入多個值時,只有一個值被附加到密鑰'標題'。另外,它說titles.push不是一個函數。推動數組;將多個值存儲到單個密鑰中

//get the title from user 
var title = prompt("What would you like your title to be?"); 
localStorage.setItem(title, editElem.innerHTML); 

//save the editor contents to local storage based on title 
document.getElementById("update").innerHTML = "Edits saved!"; 
var theDiv = document.getElementById("Contentable"); 
var content = document.createTextNode(title); 
theDiv.appendChild(content); 
var br = document.createElement("br"); 
theDiv.appendChild(br); 

//save the all titles in array so you know what documents exist 
var titles = localStorage.getItem("titles"); 
if(titles == null) 
    titles = new Array(); 
if(titles.indexOf(title) < 0) 
    titles.push(title); 
localStorage.setItem("titles", titles); 
+0

'如果(titles.indexOf(標題)<0)'將永遠是一個'新的Array()真' –

+2

決不省略括號,尤其是不好的壓痕。它使你的代碼不可讀 – poe123

+0

'titles'必須是'title.push'的一個數組作爲函數。我不認爲'localStorage.getItem'返回的內容通常是一個字符串。 - **如果您希望在本地存儲中保存JS對象(如HTML),則必須使用'JSON.stringify'。** – evolutionxbox

回答

0

使用以下對象將標題推送到存儲。請注意0​​如何從Array轉換爲string,以及JSON.parse的做法相反。

var titlesStore = 
     { 
      Count: function() { 
       var stack = JSON.parse(localStorage.getItem("titles")); 
       if (!stack) 
        return 0; 
       return stack.length; 
      }, 
      Peek: function() { 
       var stack = JSON.parse(localStorage.getItem("title")); 
       if (!stack) 
        stack = []; 
       if (stack.length > 0) 
        return stack.pop(); 
      }, 
      Push: function (token) { 
       var stack = JSON.parse(localStorage.getItem("titles")); 
       if (!stack) 
        stack = []; 
       stack.push(token); 
       localStorage.setItem("title", JSON.stringify(stack)); 
      }, 
      // more methods to you might wish to implement: search, insert, etc. 
     } 

    // usage: 
    titlesStore.Push("new title"); // sets the last title 
    titlesStore.Peek(); // gets the last title ; 
相關問題