使用jquery选中/取消选中一个复选框

时间:2015-04-09 18:33:03

标签: javascript jquery checkbox

我有一个包含30多个复选框的HTML页面(

如何配置此脚本以仅记住我选中的复选框(仅记住已选中或未选中的复选框)

这是我使用的脚本:

$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('input').prop('checked', test || false);
});

$('input').on('change', function() {
    localStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});

2 个答案:

答案 0 :(得分:0)

$('input')匹配所有输入。给它一个更具体的选择器(最好是你想要记住的输入的id

答案 1 :(得分:0)

此代码保存会话之间所有复选框的状态:

$('input[type=checkbox]').each(function(idx) {
  this.checked= localStorage.getItem('input'+idx) === 'true';
});

$('input[type=checkbox]').each(function(idx) {
  $(this).click(function() {
    localStorage.setItem('input'+idx, this.checked);
  });
});

Fiddle 1

<小时/> 如果添加,切换或删除输入,您将需要一种不同的方法。

如果每个输入都有id,则可以改为使用此代码:

$('input[type=checkbox]').each(function(idx) {
  this.checked= localStorage.getItem('input'+this.id) === 'true';
});

$('input[type=checkbox]').click(function() {
  localStorage.setItem('input'+this.id, this.checked);
});

Fiddle 2