2017-05-26 61 views
0

我的localStorage返回null,我不知道爲什麼,read函數沒有被使用,但只是爲了幫助,我反正把它放了。 Chrome表示無法將innerHTML置入null,並且我的疑難解答警報信息也會返回null,但代碼將結束。任何幫助將是有用的,謝謝。
該Cookie:HTML localStorage返回NULL

<!doctype html> 
<html> 
    <head> 
    <cookie> 
     <script>localStorage.setItem('id',Math.floor(Math.random()*10)) 
</script> 
    </cookie> 
    </head> 
    <body> 
    <script>var id = localStorage.getItem('id') 
    alert(id)</script> 
    </body> 
</html> 

腳本:

<!doctype html> 
<html> 
    <head> 

    <script> 
    var theId=localStorage.getItem('id') 


    function change(id,target){ 
     var info = localStorage.getItem(id); 
     alert(info) 
     document.getElementById(target).innerHTML=info; 
    } 
    function read(){ 
     var element=document.createElement('h1') 
     element.innerHTML='You Want To Read' 
     document.body.appendChild(element) 
     alert('debug') 

    } 
    </script> 
    </head> 
    <body> 
    <input type="button" value="Read" name="read_story" id="read_story" 
onclick=read();change(theId,info)> 
    <p id='info'>initial</p> 
    </body> 
    <script> 
    alert('debug'); 

    </script> 
</html> 
+0

你試過只是設置一個硬編碼的值,並看到後,如果getItem的作品? – ThisGuyHasTwoThumbs

回答

1

你誤解的錯誤消息。

如果它不能設置innerHTMLnull那麼你有something.innerHTML = a_value。這是somethingnull與本地存儲沒有任何關係。

change(theId,info)info是一個變量。它是對id="info"元素的引用。

您在這裏使用它:document.getElementById(target)

info(現在的target)被轉換成字符串("[object HTMLParagraphElement]")。

沒有與id="[object HTMLParagraphElement]"元素,所以你得到null

當您調用該函數時,您需要傳遞一個字符串,而不是一個變量。

+0

謝謝,但我該如何將該變量作爲字符串傳遞給該函數,以便將localStorage.getItem('id')返回到innerHTML中? –

+0

@JohnHao - 你把它引號。 – Quentin