我想要一个按钮,用于选中或取消选中所有复选框。
这是我的标记:
<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');
});
但它没有按预期工作:
- 检查全部,有效
- 全部取消选中,有效
- 再次检查一切,没有任何反应
可能是什么错误?
最佳答案
$("#addAll").click(function() {
$("#container input:checkbox").prop('checked', true);
});
$("#removeAll").click(function() {
$("#container input:checkbox").prop('checked',false);
});
<小时/>
这可能是jquery中的一个错误,因为使用 native setAttribute和removeAttribute工作正常。
https://jsfiddle.net/jz5p57k9/
我已经为 Jquery 团队打开了一个错误,您可以在这里关注:
https://github.com/jquery/jquery/issues/3242#issuecomment-234315378
关于.attr和.prop的区别,请看这个问题:.prop() vs .attr()
关于javascript - 如何创建带有复选框的 "check/uncheck all"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38507134/