使用jQuery实现不同div内全选复选框控制同区域其他复选框功能
实现方案
步骤1:修改HTML添加全选标识
给每个分组下标注「Select All」的复选框新增类名select-all,方便后续识别绑定事件,修改后对应代码示例:
<!-- 第一组全选框 --> <div><input type="checkbox" name="action" class="select-all" value="0" /> Select All</div> <!-- 第二组全选框 --> <div><input type="checkbox" name="action" class="select-all" value="26" />Select All</div>
步骤2:编写交互逻辑
方式1:jQuery实现(项目已引入jQuery时推荐使用,代码更简洁)
$('.select-all').on('change', function() { // 获取当前全选框所属的分组容器 const currentGroup = $(this).closest('div').parent(); // 同步分组内除全选外所有复选框的选中状态 currentGroup.find('input[type="checkbox"]').not('.select-all').prop('checked', $(this).prop('checked')); })
方式2:原生JS实现(无需额外依赖)
document.querySelectorAll('.select-all').forEach(selectAllBtn => { selectAllBtn.addEventListener('change', function() { // 获取当前全选框所属的分组容器 const currentGroup = this.closest('div').parentElement; // 遍历同步分组内普通复选框的选中状态 currentGroup.querySelectorAll('input[type="checkbox"]').forEach(checkbox => { if (!checkbox.classList.contains('select-all')) { checkbox.checked = this.checked; } }) }) })
可选优化:反向联动效果
如果需要实现「分组内所有普通复选框都手动选中时自动勾选全选、任意普通复选框取消选中时自动取消全选」的效果,可额外添加如下代码(以jQuery为例):
$('input[type="checkbox"]').not('.select-all').on('change', function() { const currentGroup = $(this).closest('div').parent(); const allNormalChecks = currentGroup.find('input[type="checkbox"]').not('.select-all'); const groupSelectAll = currentGroup.find('.select-all'); groupSelectAll.prop('checked', allNormalChecks.length === allNormalChecks.filter(':checked').length); })
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

