jQuery 实现input框checkbox全选
点击全选或者取消全选,单击选中全部自定勾选全选
<div>
<label>
<input name="checkAll" type="checkbox">
<span>全选</span>
</label>
</div>
<div>
<label>
<input name="checkItem" type="checkbox">
<span>1</span>
</label>
<label>
<input name="checkItem" type="checkbox">
<span>2</span>
</label>
<label>
<input name="checkItem" type="checkbox">
<span>3</span>
</label>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script type="text/javascript">
// 全选按钮添加改变事件
$('input[name="checkAll"]').change(function(){
/*
判断当前checked的值为true还是false
checked=true就设置其他复选框为选中状态
checked=false就设置其他复选框为未选中状态
*/
/*
prop是对于HTML元素本身就带有的固有属性
attr是对于HTML元素我们自定义的加在标签中的属性
*/
if(this.checked){
// 类似checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果
$('input[name="checkItem"]').prop('checked',true)
}else{
$('input[name="checkItem"]').prop('checked',false)
}
})
// 每个单选按钮添加改变事件
$('input[name="checkItem"]').change(function(){
// 初始量进行计数选中的数量
let count = 0;
// 遍历所有单选按钮,查看是否选中
$('input[name="checkItem"]').each(function(){
if(this.checked){
count++
}
})
// 获取所有单选按钮数量
let length = $('input[name="checkItem"]').length;
// 如果选中的数量count等于单选按钮的数量就显示全选
if(count == length){
$('input[name="checkAll"]').prop('checked',true)
}else{
$('input[name="checkAll"]').prop('checked',false)
}
})
</script>