jQuery如何实现手动勾选全部子复选框后自动选中全选框?
实现方案
你需要给所有.select类的子复选框绑定点击事件,每次点击时统计已选中的子复选框数量,和总子复选框数量做比对,一致则自动勾选全选框,否则取消全选框的选中状态即可,完整实现代码如下:
HTML 结构(和你当前的结构一致)
<input type='checkbox' id='selectAll'/> <input type='checkbox' id='select1' class='select'/> <input type='checkbox' id='select2' class='select'/>
完整 jQuery 逻辑
// 原有全选框控制子复选框逻辑,可简化为一行,无需if判断 $('#selectAll').click(function(){ $(".select").prop("checked", $(this).prop("checked")); }); // 新增子复选框反向联动全选框逻辑 $('.select').click(function() { // 子复选框总数量 const total = $('.select').length; // 已选中的子复选框数量 const checkedCount = $('.select:checked').length; // 两者相等则勾选全选框,否则取消 $('#selectAll').prop('checked', total === checkedCount); });
兼容动态新增子复选框的优化写法
如果你的子复选框是后续动态渲染到页面中的,直接绑定click事件不会生效,可以改用事件委托的写法,把事件绑定到子复选框的固定父级元素上即可(示例中假设父级元素id为checkGroup,你可以替换为实际的父元素选择器):
$('#checkGroup').on('click', '.select', function() { const total = $('.select').length; const checkedCount = $('.select:checked').length; $('#selectAll').prop('checked', total === checkedCount); });
内容的提问来源于stack exchange,提问作者Rao DYC
相关产品推荐
相关产品推荐

