JS如何实现全选以及联动效果
其中notice为整体的渲染输入框,通过他绑定事件委托到子集,因为子集为动态渲染
$(".notice").on("change", ".notice_nav input[type='checkbox']", function () {
// 获取全选框状态
const isChecked = $(this).prop("checked");
// 设置所有子复选框状态
$(".notice_box .checkbox_id input").prop("checked", isChecked);
// 计算选中数量(直接使用子项总数或0)
const checkedCount = isChecked
? $(".notice_box .checkbox_id input").length
: 0;
$(".checked_num").text(checkedCount);
});
同时规定并限制为全选框的监听事件,当全选框改变的时候,根据全选框的状态来更新所有子选择框的选中,确保全选和子选择的一致性,同时计算所有被选择的子选择框数量,当存在的时候是数量,不存在的时候为0
然后再调校子选择框位
$(".notice").on("change", ".notice_box .checkbox_id input", function () {
// 获取所有子复选框
const $checkboxes = $(".notice_box .checkbox_id input");
// 计算选中状态
const checkedCount = $checkboxes.filter(":checked").length;
const allChecked = checkedCount === $checkboxes.length;
// 同步全选框状态
$(".notice_nav input").prop("checked", allChecked);
// 更新界面显示
$(".checked_num").text(checkedCount);
});
同样获取到所有的子集状态,并获得选中的子集长度,同时将长度合并并赋值给变量
同步去操控全选框的位置
更新数据