2013-07-22 80 views
1

我有一個用於5個html頁面的localStrg.js文件,頁面內有一些頁面中不存在的元素。我想驗證是否這樣的元素存在,如果它得到它的價值,並把它作爲缺省的/我有這樣的js文件:如何使用javascript和localStorage驗證元素是否存在於html中?

function initialize() { 
       // Test to see if we support the Storage API 
       var SupportsLocal = (('localStorage' in window) && window['localStorage'] !== null); 
       var SupportsSession = (('sessionStorage' in window) && window['sessionStorage'] !== null); 

       // if either one is not supported, then bail on the demo 
       if (!SupportsLocal || !SupportsSession) { 
        document.getElementById('infoform').innerHTML = "<p>Sorry, this browser does not support the W3C Storage API.</p>"; 
        return; 
       } 
       // if the localStorage object has some content, restore it 
       if (window.localStorage.length != 0) { 

         for(i=0;i<window.localStorage.length;i++){ 
          if(document.getElementById(window.localStorage.key(i))==!null){ 
          alert("entered for"); 
           getLocalContent(window.localStorage.key(i)); 
           alert("got local content"); 
           if(document.getElementById(window.localStorage.key(i)).type == "checkbox"){ 
            alert("if"); 
            document.getElementById(window.localStorage.key(i)).checked = true; 

           } 
          alert("out of if"); 
         } 
       } 
         alert("out of for"); 

       } 
} 

function storeLocalContent(elementId,value){ 
    window.localStorage.setItem(elementId,value); 
} 

function getLocalContent(elementId){ 
    document.getElementById(elementId).value = window.localStorage.getItem(elementId); 
} 

function clear(){ 
    window.localStorage.clear(); 
} 

function removeItem(elementId){ 
    window.localStorage.removeItem(elementId); 
} 

function isChecked(elementId, value){ 
    if(document.getElementById(elementId).checked == false){ 
     removeItem(elementId); 
    } 
    else if(document.getElementById(elementId).checked === true){ 
     storeLocalContent(elementId, value); 
    } 
} 


window.onload = function(){ 
    initialize(); 

} 

,但每次我取「出來的對」

+0

您的運營商檢查,看看是否該元素爲null是錯誤的。在js它是'!==' – scrappedcola

回答

1

的在這一行比較操作是錯誤的:

if(document.getElementById(window.localStorage.key(i))==!null){ 

應該

if(document.getElementById(window.localStorage.key(i))!==null){ 
+0

哦,好的!會看看它是否有效,謝謝! – Ch32k0

+0

非常感謝,它的工作! – Ch32k0

相關問題