我有一个简单的jQuery函数,可以根据复选框状态切换类。这是代码:
jQuery的:
$('input[name$="bg-noise-option"]').click(function(){
var targetClass = $(this).data('at');
$('.' + targetClass).toggleClass('bg-noise');
});
HTML:
<div class="checkbox">
<label>
<input type="checkbox" name="bg-noise-option" data-at="page-wrap" checked>
Body <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option" data-at="btn">
Elements <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option" data-at="header, .navbar">
Top Header <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option" data-at="page-header-wrap">
Page Header <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option" data-at="site-footer">
Footer <br>
</label>
</div>
问题: 如何为每个选中的复选框创建一个cookie?我只是试图给这些复选框留下一些记忆......不确定最好的方法。
我怀疑某种类型的.each(function)
应该这样做,但我仍然是javascript新手。我尝试了以下内容:
$.each(function(){
$.cookie('bg-noise-cookie', $(this).data('at'), {expires:365, path: '/'});
})
但当然,只为最近选中的复选框创建一个cookie。如何为每个创建一个独特的cookie?或者我甚至需要?也许有一种方法可以将它们存储在一个cookie(一个数组?)中,然后只需在页面加载时引用该数组来检查复选框?
非常有必要深入了解。
答案 0 :(得分:1)
这假设您使用JQuery Cookie Plugin,因为我看到您在问题中引用了它。
你在这里。在任何复选框点击时创建并更改单个cookie文件,仅存储与复选框对应的值的数据。
在页面加载时,它会检索该JSON字符串,将其转换回对象,然后循环执行,对任何匹配属性的框应用检查。
代码测试和工作。
HTML:我添加了&#39; []&#39;到您的复选框以正确分组它们并删除任何默认的复选框。
<div class="checkbox">
<label>
<input type="checkbox" name="bg-noise-option[]" data-at="page-wrap">
Body <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option[]" data-at="btn">
Elements <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option[]" data-at="header, .navbar">
Top Header <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option[]" data-at="page-header-wrap">
Page Header <br>
</label>
<label>
<input type="checkbox" name="bg-noise-option[]" data-at="site-footer">
Footer <br>
</label>
</div>
JQuery:使用$ .cookie()插件
<script type="text/javascript">
$(document).ready(function() {
// check for cookie on load
if( $.cookie('chk_ar') ) {
console.log($.cookie('chk_ar'));
var chk_ar = $.cookie('chk_ar');
// convert string to object
chk_ar = $.parseJSON(chk_ar);
console.log(chk_ar);
// loop through and apply checks to matching sets
$.each(chk_ar, function(index, value) {
console.log(value);
$('input').filter('[data-at="'+value+'"]').prop('checked', true);
});
}
});
// handle checkboxes
$('input[name="bg-noise-option[]"').on('click', function() {
var check_array = [];
// add to array
$(':checked').each(function() {
check_array.push($(this).attr('data-at'));
});
// stringify array object
check_array = JSON.stringify(check_array);
console.log(check_array);
// set cookie
$.cookie('chk_ar', check_array, {path:'/'});
});
</script>