2017-05-26 94 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