开发者

Why is my localStorage code not working?

开发者 https://www.devze.com 2023-03-21 22:45 出处:网络
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

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号