使用jquery选中并取消选中所有复选框

vlo*_*yan 4 javascript checkbox jquery

我正在使用此脚本来检查并取消选中所有复选框:

$('#checkall').click(function () {
    var checked = $(this).data('checked');
    $('.chkall').find(':checkbox').attr('checked', !checked);
    $(this).data('checked', !checked);
});
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但是一旦我在"全部检查"之后取消选中几个选中的复选框,然后再次点击"取消全部检查"和"全部检查",则不再检查那些以前未选中的复选框.帮助会很棒!非常感谢你!

Jon*_*eph 11

这可能是正确的方法..

使用prop而不是attr将div中的复选框列表分组,仅用于组织目的.也可以使用checked原样,不要否定它.

$(document).ready(function() {
  $('#checkall').click(function() {
    var checked = $(this).prop('checked');
    $('#checkboxes').find('input:checkbox').prop('checked', checked);
  });
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkall" />
<label for="checkall">check / uncheck all</label>
<br/>
<br/>
<div id="checkboxes">
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />

</div>
Run Code Online (Sandbox Code Playgroud)


vsy*_*ync 8

$('#checkall').click(function(){
    var d = $(this).data(); // access the data object of the button
    $(':checkbox').prop('checked', !d.checked); // set all checkboxes 'checked' property using '.prop()'
    d.checked = !d.checked; // set the new 'checked' opposite value to the button's data object
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='checkall' data-checked='false'>check/uncheck all</button>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
Run Code Online (Sandbox Code Playgroud)


我根据触发按钮猜测了你的HTML是什么样的,但我不知道你最初如何设置data它.希望这是你编码的方式.如果没有,请告诉我.