使用HTML5 localstorage在页面刷新上保留jQuery切换状态 [英] Use HTML5 localstorage to retain jQuery toggle state on page refresh
问题描述
我刚刚了解到HTML5localstorage功能。我一直试图与jQuery切换一起实现它,以便在刷新页面时使div保持最新状态。这似乎是一个很好的cookie替代品!我很难理解如何以这种方式实现它。这是我到目前为止所尝试的:
HTML:
< div id =container< / div>
< a id =foohref =javascript:void(0);>点击我< / a>
< div id =bar>< / div>
< / div>
CSS:
#container {width:200px;身高:220px;}
#foo {
display:block;向左飘浮;
width:200px;高度:20像素;
text-align:center;
}
#bar {
display:none;向左飘浮;
height:200px;宽度:200像素;
背景:#000000;
}
jQuery并试图在localstorage中学习 here :
$(document).ready(function(){
$('#foo')。click(function(){
$(this).siblings() .toggle();
localStorage.setItem(display,block);
});
var block = localStorage.getItem(block);
if(block){
$('#bar')。show()
}
});
这里是小提琴。
我所做的绝对不行。我在这里看到了类似的问题,因此这个< a>是一个很好的例子。然而,这个答案对我没有帮助,看起来非常复杂。
我试图了解如何在非常基本的层次上使用localstorage来保存切换状态。
试试<$> p $ p>
$(document).ready(function(){
$('#foo')。click(function(){
$(this).siblings( ).toggle();
//你需要传递字符串值,你的变量display& block没有被定义
localStorage.setItem('display',$(this).siblings()。is (':visible'));
});
var block = localStorage.getItem('display');
if(block =='true'){
$ ('#bar')。show()
}
});
演示:小提琴
I just learned about the HTML5 "localstorage" function. I have been attempting to implement it in conjunction with jQuery toggle in order to cause a div to remain in it's most recent state when a page is refreshed. This seems like a great alternative to a cookie! I am having a lot of trouble understanding how to implement it in this way. Here is what I have tried so far:
HTML:
<div id="container"</div>
<a id="foo" href="javascript:void(0);">Click Me</a>
<div id="bar"></div>
</div>
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;
}
jQuery and attempt at localstorage as learned here:
$(document).ready(function(){
$('#foo').click(function() {
$(this).siblings().toggle();
localStorage.setItem(display, block);
});
var block = localStorage.getItem(block);
if(block){
$('#bar').show()
}
});
Here is the fiddle.
What I am doing is definitely not working. I have seen somewhat similar questions here on SO this being a good example. However this answer hasn't helped me and seems very complex.
I am simply attempting to understand how to use localstorage at a very basic level in order to save a toggle state.
Greatly appreciate any advice or help.
Try
$(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()
}
});
Demo: Fiddle
这篇关于使用HTML5 localstorage在页面刷新上保留jQuery切换状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!