2013-10-09 280 views
0

我想象一個用普通JS編寫的待辦事項列表,而不使用框架來查看localStorage跨瀏覽器的兼容性。跨瀏覽器localStorage

劇本是

function addText(){ 
var input = document.getElementById('input').value; 
date = new Date(); 
var time = date.getTime(); 
if (input !== "") { 
    localStorage.setItem(time,"lalala"); 
    document.getElementById('input').value = ''; 
}}; 

function loadText(){ 
if (window.localStorage) { 
     for(var i in window.localStorage){ 
      console.log(i+"--------theiiiiiii"); 
      var z = localStorage.getItem(i); 
      console.log(z+"--------you keep me satisfied"); 
    } 
} else { 
    alert("Your Browser does not support LocalStorage."); 
} 
} 

現在,我Chrome的工作,在Firefox差不多,戲我得到的設定值加上所有的localStorage的運營商。有人知道這個解決方案嗎?

1381311087810--------theiiiiiii 
lalala--------you keep me satisfied 
length--------theiiiiiii 
null--------you keep me satisfied 
key--------theiiiiiii 
null--------you keep me satisfied 
getItem--------theiiiiiii 
null--------you keep me satisfied 
setItem--------theiiiiiii 
null--------you keep me satisfied 
removeItem--------theiiiiiii 
null--------you keep me satisfied 
clear--------theiiiiiii 
null--------you keep me satisfied 

回答

1

嘗試通過上市僅鍵:

function loadText(){ 
    if (window.localStorage) { 

     /// list all keys from object 
     var keys = Object.keys(localStorage); 

     for(var i, key; key = keys[i]; i++) { 
      console.log(key + "--------theiiiiiii"); 
      var z = localStorage.getItem(key); 
      console.log(z + "--------you keep me satisfied"); 
     } 
    } else { 
     alert("Your Browser does not support LocalStorage."); 
    } 
} 
+0

謝謝!與此同時,我設法讓它在Opera中工作。在我的情況下,這是關鍵和價值作爲一個多層次的JSON。這樣我就可以忽略解釋localStorage時的任何瀏覽器故障。 –

+0

你是怎麼做到的@DeckPope?謝謝! – bomblike