使用HTML5 localstorage在页面刷新时保留jQuery切换状态

Hel*_*rld 5 jquery html5 local-storage

我刚刚了解了HTML5"localstorage"功能.我一直在尝试与jQuery切换一起实现它,以便在刷新页面时使div保持在最新状态.这似乎是一个很好的替代cookie!我在理解如何以这种方式实现它时遇到了很多麻烦.这是我到目前为止所尝试的:

HTML:

<div id="container"</div>
    <a id="foo" href="javascript:void(0);">Click Me</a>
    <div id="bar"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

#container {width:200px; height:220px;}

#foo {
    display:block; float:left;
    width:200px; height:20px; 
    text-align:center;
}
#bar {
    display:none; float:left;
    height:200px; width:200px;
    background:#000000;
}
Run Code Online (Sandbox Code Playgroud)

jQuery和在localStorage的尝试为教训在这里:

$(document).ready(function(){
    $('#foo').click(function() {
    $(this).siblings().toggle();
    localStorage.setItem(display, block);
});
    var block = localStorage.getItem(block);
    if(block){
        $('#bar').show()
    }
});
Run Code Online (Sandbox Code Playgroud)

是小提琴.

我在做什么绝对不行.我在这里看到了一些类似的问题,是一个很好的例子.然而,这个答案对我没有帮助,看起来非常复杂.

我只是试图了解如何在非常基本的级别使用localstorage以保存切换状态.

非常感谢任何建议或帮助.

Aru*_*hny 8

尝试

$(document).ready(function () {
    $('#foo').click(function () {
        $(this).siblings().toggle();
        //you need to pass string values, your variables display & block was not defined
        localStorage.setItem('display', $(this).siblings().is(':visible'));
    });
    var block = localStorage.getItem('display');
    if (block == 'true') {
        $('#bar').show()
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴