同一父div内元素显隐问题:选中对应选项无法单独控制.option-other
解决选择器切换时精准控制父组内元素显示/隐藏的问题
我之前也踩过类似的坑!你遇到的问题核心是没有精准定位到当前选择器所在的.other-row父组,导致触发事件时操作了页面上所有的.option-other元素,才会出现选一个other就显示两个的情况。
问题根源
你尝试的.parent()方法只能获取当前元素的直接父节点,如果你的.select-toggle直接父元素不是.other-row,那这个方法就找不到目标容器;而.closest()是向上遍历DOM树,直到找到匹配的第一个元素,这才是你需要的正确用法。
具体解决方案(jQuery版)
绑定change事件时,先通过closest('.other-row')锁定当前选择器所在的父组,再在这个组内查找.option-other进行显示/隐藏操作:
$('.select-toggle').on('change', function() { // 精准定位当前选择器所属的.other-row父组 const $targetRow = $(this).closest('.other-row'); // 只操作当前组内的.option-other const $otherInput = $targetRow.find('.option-other'); if ($(this).val() === 'other') { $otherInput.show(); } else { $otherInput.hide(); } });
对应HTML结构参考
确保你的DOM结构是每个.select-toggle都包裹在独立的.other-row里,这样上面的代码才能正确匹配:
<div class="other-row"> <select class="select-toggle"> <option value="option1">问题集1-选项1</option> <option value="option2">问题集1-选项2</option> <option value="other">Other</option> </select> <div class="option-other" style="display: none;"> 问题集1的其他选项输入区 </div> </div> <div class="other-row"> <select class="select-toggle"> <option value="optionA">问题集2-选项A</option> <option value="optionB">问题集2-选项B</option> <option value="other">Other</option> </select> <div class="option-other" style="display: none;"> 问题集2的其他选项输入区 </div> </div>
原生JS版本(如果不用jQuery)
如果你项目里没引入jQuery,用原生JS也能实现相同逻辑:
// 给所有.select-toggle绑定事件 document.querySelectorAll('.select-toggle').forEach(selectEl => { selectEl.addEventListener('change', function() { // 找到当前选择器的父组.other-row const targetRow = this.closest('.other-row'); // 获取组内的.option-other const otherInput = targetRow.querySelector('.option-other'); if (this.value === 'other') { otherInput.style.display = 'block'; } else { otherInput.style.display = 'none'; } }); });
关键要点总结
- 用
closest('.other-row')替代parent(),因为它能跨层级向上查找第一个匹配的父容器,适配更多DOM结构场景; - 始终在锁定的父容器内查找目标元素(
.find()或querySelector()),避免全局选择器影响其他无关元素。
内容的提问来源于stack exchange,提问作者randy
相关产品推荐
相关产品推荐

