如何使用复选框创建“选中/取消选中全部”?

时间:2016-07-21 14:35:12

标签: javascript jquery html

我想要一个按钮,选中或取消选中所有复选框。

这是我的标记:

<div id="container">
  <input type="checkbox">
  <input type="checkbox">
  <input type="checkbox">
  <input type="checkbox">
</div>
<button type="button" id="addAll">add all</button>
<button type="button" id="removeAll">remove all</button>

这是我的剧本:

$("#addAll").click(function() {
  $("#container input:checkbox").attr('checked', 'checked');
});
$("#removeAll").click(function() {
  $("#container input:checkbox").removeAttr('checked');
});

但它没有按预期工作:

  • 全部检查,工作
  • 取消选中所有,正常工作
  • 再次检查,没有任何反应

可能是什么错误?

请参阅this fiddle

1 个答案:

答案 0 :(得分:2)

$("#addAll").click(function() {
  $("#container input:checkbox").prop('checked', true);
});
$("#removeAll").click(function() {
  $("#container input:checkbox").prop('checked',false);
});

这可能是jquery中的一个错误,因为使用原生setAttribute和removeAttribute可以正常工作。

https://jsfiddle.net/jz5p57k9/


我已经为Jquery团队打开了一个bug,你可以在这里关注它: https://github.com/jquery/jquery/issues/3242#issuecomment-234315378

。对于.attr和.prop之间的区别,请看这个问题:.prop() vs .attr()