我想在cookie中存储一个复选框状态:
<script type="text/javascript">
$(document).ready(function(){
var checkbox = $('#boxlawreg :checkbox'),
checkboxCookieName = 'checkbox-state';
checkbox.prop('checked', +$.cookie(checkboxCookieName));
checkbox.click(function() {
$.cookie(checkboxCookieName, +this.checked);
});
});
</script>
它工作得很好,但我有7个复选框,如果我检查一个,重新加载我的网站,所有的复选框都是检查。
看起来像:
<input type="checkbox" name="option1" value="1">
<input type="checkbox" name="option2" value="2">
<input type="checkbox" name="option3" value="3">
<input type="checkbox" name="option4" value="4">
有什么想法吗?
(Ps:对不起英语,我是法国人)
答案 0 :(得分:3)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var checkbox = $('#boxlawreg').find(':checkbox'), checkboxCookieName = 'checkbox-state';
checkbox.each(function () {
$(this).attr('checked', $.cookie(checkboxCookieName + '|' + $(this).attr('name')));
});
checkbox.click(function () {
$.cookie(checkboxCookieName + '|' + $(this).attr('name'), $(this).prop('checked'));
});
});
</script>
</head>
<body>
<div id="boxlawreg">
<input type="checkbox" name="option1" value="1" />1<br />
<input type="checkbox" name="option2" value="2" />2<br />
<input type="checkbox" name="option3" value="3" />3<br />
<input type="checkbox" name="option4" value="4" />4<br />
</div>
</body>
</html>