直接上例子
<input type="checkbox" class="checkAll">
<div id="check_wrap">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
$('.checkAll').on('click', function(){
let checked = $(this).attr('checked');
$('#check_wrap :checkbox').attr('checked', checked);
//你会发现,点击勾选全部可以实现,但当你再点击全选时,多选框没被取消
//原因看以下输出
console.log($(this).attr('checked')); //checked undefined
console.log($(this).prop('checked')); //true false
console.log($(this).is(':checked')); //true false
console.log($(this)[0].checked); //true false
})
一目了然,当checked=undefined时,设置值就失败了。原因是jQuery 1.6版本对attr()的改动。官方是这么说的。
从jQuery 1.6开始,尚未设置的属性.attr()方法返回undefined。要检索和更改DOM属性,如checked
,selected
或disabled
元素形式的元素状态,使用.prop()方法。
示例代码段中的三种方式均可满足需求。