如何使用JavaScript实现下拉框切换时对应div的显示与隐藏
功能调整实现方案
推荐方案:预定义DOM + 显隐控制
该方案无需每次动态拼接HTML,性能更优,也能保留用户临时输入的内容:
- 调整HTML中
id="other"的节点内容,默认设为隐藏:
<!-- 替换原有空的<div id="other"></div>节点 --> <div id="other" style="display: none;"> <div class="group"> <div class="col-25"> <label>请说明“其他”具体指代</label> </div> <div class="col-75"> <input type="text" name="otherInput" required> </div> <span class="highlight"></span> <span class="bar"></span> </div> </div>
- 修改
otherFunc函数逻辑:
function otherFunc() { const selectBox = document.getElementById("selectBox"); const selectedValue = selectBox.options[selectBox.selectedIndex].value; const otherDiv = document.getElementById("other"); if (selectedValue === "Other") { otherDiv.style.display = "block"; } else { otherDiv.style.display = "none"; // 若需要切换选项后清空之前的输入,可取消注释下一行 // otherDiv.querySelector('input[name="otherInput"]').value = ""; } }
兼容原有逻辑的修改方案
如果不想改动HTML结构,沿用原有动态插入DOM的逻辑,直接修改JS函数即可:
function otherFunc() { const selectBox = document.getElementById("selectBox"); const selectedValue = selectBox.options[selectBox.selectedIndex].value; const otherDiv = document.getElementById("other"); if (selectedValue === "Other") { otherDiv.innerHTML = ' <div class="group"><div class="col-25"><label>请说明“其他”具体指代</label></div><div class="col-75"><input type="text" name="otherInput" required></div><span class="highlight"></span><span class="bar"></span></div>'; } else { otherDiv.innerHTML = ""; } }
内容的提问来源于stack exchange,提问作者developerg1000
相关产品推荐
相关产品推荐

