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

JavaScript新手求助:选择Engineer时无法显示隐藏下拉列表

Fixing Your Dropdown Visibility Issue

Hey there! Let's work through this problem step by step—you're really close, just a few small syntax and logic tweaks needed to get this working.

Let's Break Down the Issues in Your Code

  1. Incorrect JavaScript Syntax for CSS Properties
    You used CSS-style colon syntax (y.style.visibility : visible;) instead of JavaScript's assignment operator. In JS, we set style properties with an equals sign, and the value needs to be in quotes:

    y.style.visibility = "visible"; // Correct syntax
    
  2. Case Sensitivity Mismatch
    Your condition checks for v=="Engineer", but you need to make sure this matches the value attribute of your HTML <option> exactly. If your HTML uses lowercase (like <option value="engineer">Engineer</option>), the condition won't trigger. Always align the case between your JS check and HTML values.

  3. Missing Initial Hidden State
    The second dropdown (id="a") needs to start hidden so the toggle is noticeable. Add an inline style to it in your HTML:

    <select id="a" style="visibility: hidden;">...</select>
    
  4. Reset Visibility for Other Options
    It's good practice to re-hide the dropdown when the user selects a different role (pilot/technician) so the UI stays clean.

Full Working Example

Here's the corrected code with all fixes included:

<!-- Main Role Dropdown -->
<select onchange="func(this.value)">
  <option value="">Select a Role</option>
  <option value="engineer">Engineer</option>
  <option value="pilot">Pilot</option>
  <option value="technician">Technician</option>
</select>

<!-- Hidden Division Dropdown -->
<select id="a" style="visibility: hidden;">
  <option value="wing">Wing Division</option>
  <option value="engine">Engine Division</option>
</select>

<script type="text/javascript">
function func(v) {
  const divisionDropdown = document.getElementById("a");
  if(v === "engineer"){
    divisionDropdown.style.visibility = "visible";
  } else {
    divisionDropdown.style.visibility = "hidden";
  }
}
</script>

Optional: Using display Instead of visibility

If you don't want the hidden dropdown to take up space on the page, you can use display instead of visibility:

<!-- Initial state -->
<select id="a" style="display: none;">...</select>
// In the function
if(v === "engineer"){
  divisionDropdown.style.display = "block";
} else {
  divisionDropdown.style.display = "none";
}

内容的提问来源于stack exchange,提问作者Mohammed Rafeeq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:17:45