2017-05-26 23 views
0

localStorageはnullを返します。なぜ、読み込み関数が使用されていないのかわかりませんが、とにかくそれを置くのに役立ちます。 ChromeはinnerHTMLをnullにすることはできず、トラブルシューティングのアラート情報もnullを返しますが、コードは最後まで進みます。どんな助けも役に立つでしょう、ありがとう。
クッキー:HTML localStorage Returns 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です。 nullはローカルストレージとは関係ありません。somethingです。

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