使用jQuery实现表格内父子复选框级联勾选/取消功能
表格内父子复选框联动实现
现有页面结构
<table id="myTable"> <tr> <td> <label> <input type="checkbox" class="parent" name="mod[6]" value="1"> </label> </td> <td><span>Parent Module</span></td> <td> <label> <input type="checkbox" name="mod[7]" value="1"> Sub Module </label> <label> <input type="checkbox" name="mod[8]" value="1"> Sub Module </label> <label> <input type="checkbox" name="mod[9]" value="1"> Sub Module </label> </td> </tr> <tr>.....</tr> <tr>.....</tr> </table>
需满足的交互规则
- 勾选父复选框时,自动勾选当前表格行内所有子复选框,父子关联以表格行为单位
- 取消勾选父复选框时,自动取消勾选当前表格行内所有子复选框
- 只要当前行存在任意一个子复选框被勾选,对应父复选框自动保持勾选状态
- 当前行所有子复选框都未勾选时,对应父复选框自动取消勾选
补全后的完整实现代码
你原有代码仅实现了父框勾选时全选子项的逻辑,缺少父框取消联动、子项变化联动父框的逻辑,补全后代码如下:
$('#myTable').on("change", "label > input[type=checkbox]", function(e) { const $currentRow = $(this).closest('tr'); const $parentCheckbox = $currentRow.find('input[type=checkbox].parent'); const $childCheckboxes = $currentRow.find('input[type=checkbox]').not('.parent'); // 当前操作的是父复选框:同步所有子项状态 if ($(this).hasClass("parent")) { $childCheckboxes.prop("checked", $(this).prop("checked")); return; } // 当前操作的是子复选框:根据子项勾选状态同步父项 const checkedChildCount = $childCheckboxes.filter(':checked').length; $parentCheckbox.prop("checked", checkedChildCount > 0); });
逻辑说明
- 父复选框触发变更时,直接把所有子复选框的选中状态和父框同步,一行代码同时覆盖勾选、取消勾选两种场景,无需额外分支判断
- 子复选框触发变更时,统计当前行已勾选的子项数量,只要数量大于0就自动勾选父框,等于0就取消父框勾选,完全匹配联动规则
- 所有DOM查找都以当前操作元素所在的
tr为范围,不会跨表格行干扰其他组的复选框状态
内容的提问来源于stack exchange,提问作者ugsgknt
相关产品推荐
相关产品推荐

