当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why is my localStorage code not working?

问题描述:

I'm trying to make a div div disappear and stay gone even when the user comes back. It doesn't seem to do what I want. When I press the button, nothing happens. Not even the value of the localStorage changes...

localStorage.done = localStorage.done || false;

$('#myButton').addEventListener('click', function() {

if (!localStorage.done) {

localStorage.done = true;

$('#myDiv').style.display = "none";

}

});

网友答案:

You code for the localStorage is actually working (even if its suggested to use its getter/setter methods instead of direct property access).

Your problem is this:

$('#myButton').addEventListener('click', function() {

jQuery does not know about .addEventListener you want just to call .bind()

    localStorage.done = localStorage.done || false;
    $('#myButton').bind('click', function() {
        if (!localStorage.done) {
            localStorage.done = true;
            $('#myDiv').hide();
        }
    });
网友答案:

localStorage only stores strings. Thus, localStorage.done = false serializes to "false". The following code will fix your problem (see JSFiddle):

 localStorage.done = localStorage.done || "false";
 document.getElementById('myButton').addEventListener('click', function() {
   if (localStorage.done == "false") {
     localStorage.done = "true";
     document.getElementById('myDiv').style.display = "none";
   }
 });

Note, to avoid confusion with jQuery, I used standard DOM "getElementById". You can also consider using "0" and "1" instead of "true" and "false".

While this restriction is not present in the W3 Specification, it applies to current browsers. See this post for more information. Happy coding!

分享给朋友:
您可能感兴趣的文章:
随机阅读: