Bar*_*ite 5 javascript checkbox jquery storage local
我在这里收集了20个这样的复选框:
<div class="cbcell">
<input type="checkbox" class="checkbox" id="home_swimming_pool" name="Basen" value="35"> Basen
</div>
<div class="cbcell">
<input type="checkbox" class="checkbox" id="home_sauna" name="Sauna" value="45"> Sauna
</div>
Run Code Online (Sandbox Code Playgroud)
使用以下代码我保存并删除本地存储中的复选框状态非常正常,dataTables的过滤功能也可正常工作.
<script type="text/javascript" >
$(':checkbox').click(function(){
var name = $(this).attr('name');
var value = $(this).val();
if($(this).is(':checked')){
console.log( name, value ); // <- debug
oTable.fnFilter(name, value,false,true,false,true);
localStorage.setItem(this.name,'checked');
} else {
console.log( name, value ); // <- debug
oTable.fnFilter('',value,false,true,false,true);
localStorage.removeItem(this.name);
}
//})
});
</script>
Run Code Online (Sandbox Code Playgroud)
请告诉我如何在页面重新加载后检索每个复选框的状态.我已经尝试了几个功能,我的最后一个立场是:
$(document).ready(function() {
if (localStorage.getItem(this.value) == 'checked'){
$(this).attr("checked",true)
}
})
Run Code Online (Sandbox Code Playgroud)
任何帮助都非常感谢.
试试这个
$(':checkbox').each(function() {
$(this).prop('checked',localStorage.getItem(this.name) == 'checked');
});
Run Code Online (Sandbox Code Playgroud)
在$(document).ready()函数中,this指的是文档,而不是复选框,如$(':checkbox').click().另外,如果你考虑一下,你真的需要一种方法来遍历你的复选框.这就是.each()的用武之地.在$(':checkbox').each()函数内,this将引用一个特定的复选框
另外,检查运行代码的浏览器是否实际支持localStorage是个好主意,否则您将收到错误.
一个简单的方法是将所有东西都包裹在一个 if (window.localStorage) { /* code here */}
改良版
if (window.localStorage) {
$('.cbcell').on('click',':checkbox',function(){
var name = this.name;
var value = this.value;
if($(this).is(':checked')){
oTable.fnFilter(name, value,false,true,false,true);
//shorthand to check that localStorage exists
localStorage && localStorage.setItem(this.name,'checked');
} else {
oTable.fnFilter('',value,false,true,false,true);
//shorthand to check that localStorage exists
localStorage && localStorage.removeItem(this.name);
}
});
$(document).ready(function () {
$(':checkbox').each(function() {
$(this).prop('checked',localStorage.getItem(this.name) == 'checked');
});
});
}
Run Code Online (Sandbox Code Playgroud)
最后,我建议花一些时间浏览http://try.jquery.com/上的优秀 Try jQuery教程.