问题
I wanted to ask why innerHTML is not working in the following code:
document.getElementById('text').innerHTML = localStorage["mytext"];
The element with the id text is a div element. localStorage is giving me the right String if I use it with alert, what could the error be?
回答1:
Make sure the div exists before trying to reference it,
window.addEventListener("load",function() {
document.getElementById('text').innerHTML = localStorage.getItem("mytext");
},false);
That will wait for the document to load before doing any modifications
回答2:
Can you check if the localStorage["text"] really returns a string? Maybe this link might help you to check the if it's really a string.
https://stackoverflow.com/a/9729103/1873758
来源:https://stackoverflow.com/questions/13691509/whats-wrong-here-why-is-innerhtml-not-working