2014-09-27 52 views
0

你好,我已經嘗試尋找線程如何在localStorage中存儲對象,並使註冊用戶使用JSON和localStorage,它正在工作(商店ID,用戶名和密碼),而無需重置或重疊用戶。如何定位登錄的localStorage密鑰?

我想添加一個登錄函數,但我無法循環訪問數組並定位到localStorage密鑰? (在這種情況下用戶:號碼)。

下面是代碼:

var User = { 
    index: window.localStorage.getItem("User:index"), 
    $form: document.getElementById("userReg"), 


    $button_register: document.getElementById("registerUser"), 
    $button_login: document.getElementById("logIN"), 

    init: function() { 
     // initialize storage index 
     if (!User.index) { 
      window.localStorage.setItem("User:index", User.index = 1); 
     } 

     User.$form.addEventListener("submit", function(event) { 
      var entry = { 
       id: parseInt(this.id_entry.value), 
       user_name: this.user_name.value, 
       password: this.password.value 
      }; 
      if (entry.id == 0) { 
       User.storeAdd(entry); 
      } 
     }, true); 


     User.$button_login.addEventListener("click", function(event) { 

      for (i = 0; i < window.localStorage.length; i++) {} 



     }, true); 


    }, 

    storeAdd: function(entry) { 
     entry.id = User.index; 
     window.localStorage.setItem("User:index", ++User.index); 
     window.localStorage.setItem("User:" + entry.id, JSON.stringify(entry)); 
    }, 


}; 



User.init(); 

回答

0

不要依靠window.localStoragelength財產。 localStorage的行爲就像一個對象,而不是像陣列

爲了通過localStorage的的密鑰來迭代,執行

for(var key in window.localStorage){ 
    var item = window.localStorage.getItem(key); 
    //do something with item 
} 
相關問題