You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript实现下拉框切换时对应div的显示与隐藏

功能调整实现方案

推荐方案:预定义DOM + 显隐控制

该方案无需每次动态拼接HTML,性能更优,也能保留用户临时输入的内容:

  1. 调整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>
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:06:05