点击.item或子复选框状态变更时切换.active类的问题咨询
代码问题根因
- 仅绑定了
.item的点击事件,且逻辑中点击到复选框时直接return终止执行,没有单独监听复选框自身的状态变更事件,导致直接点击复选框时同步逻辑完全不触发 - 类名切换逻辑中
this.checked取值错误:此处this指向的是.itemDOM元素,而非复选框,永远拿不到正确的选中状态 - 事件委托已经绑定到
.item元素,不需要再调用closest('.item')查找父元素,当前this就是目标.item元素
修复后代码
JS代码
// 公共同步方法:根据复选框状态同步active类 function syncItemState($item) { const $checkbox = $item.find('input[type="checkbox"]') $item.toggleClass('active', $checkbox.is(':checked')) } // 监听.item的点击事件(排除复选框和按钮场景) $(document).on("click", ".item", function(event) { const $target = $(event.target) // 点击到复选框、按钮时不触发当前逻辑 if ($target.is('input:checkbox') || $target.is('button')) { return } const $checkbox = $(this).find('input[type="checkbox"]') $checkbox.prop("checked", !$checkbox.is(":checked")) syncItemState($(this)) }) // 监听复选框的change事件,同步状态 $(document).on('change', '.item input[type="checkbox"]', function() { syncItemState($(this).closest('.item')) })
现有CSS和HTML代码无需修改,修复后即可实现预期效果:
- 点击
.item空白区域:同步切换复选框选中状态和.active类 - 直接点击复选框:同步切换
.active类 - 点击内部按钮无任何状态变更
内容的提问来源于stack exchange,提问作者Kyle Underhill
相关产品推荐
相关产品推荐

