如何使用jQuery实现点击互斥复选框切换显示隐藏对应内容块
代码修改方案
你原有代码的核心问题有两个:
- 事件绑定逻辑错误:将
.switch的change事件绑定放在.content的遍历循环中,会导致每个开关被重复绑定3次事件,触发异常 - 没有实现开关和内容块的匹配逻辑,也没有控制内容块的显隐状态
可用的修改后代码
const $switches = $(".switch"); const $contents = $(".content"); $switches.on("change", function () { // 保留原有互斥选中逻辑 $switches.not(this).prop("checked", false); // 先隐藏所有内容块 $contents.hide(); // 当前开关选中时展示对应内容 if (this.checked) { // 按开关顺序索引匹配对应内容块,顺序和HTML结构保持一致 const index = $switches.index(this); $contents.eq(index).show(); } })
可选优化(更稳定的匹配方案)
如果后续可能调整HTML结构顺序,避免索引对应出错,可以给每个开关增加data-target属性指定关联的内容块:
<!-- 给input标签添加data-target属性 --> <input class="switch" id="switch-novice" value="switch-novice" type="checkbox" data-target=".c1"/> <input class="switch" id="switch-intermediate" value="switch-intermediate" type="checkbox" data-target=".c2"/> <input class="switch" id="switch-expert" value="switch-expert" type="checkbox" data-target=".c3"/>
对应修改JS的显示逻辑即可:
if (this.checked) { const target = $(this).data("target"); $(target).show(); }
内容的提问来源于stack exchange,提问作者Synchro
相关产品推荐
相关产品推荐

