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

如何实现选中下拉选项时切换显示/隐藏指定<tr>元素?

实现方案:根据下拉选项切换表格行显示状态

核心需求回顾

选中「Undergraduate Program」时,隐藏id="msc"的<tr>,显示id="bsc"的<tr>;选中「Postgraduate Program」时则相反。


方案1:原生JavaScript实现

无需依赖任何库,直接通过原生DOM API完成交互:

// 获取目标元素
const progSelect = document.getElementById('prog');
const mscRow = document.getElementById('msc');
const bscRow = document.getElementById('bsc');

// 定义切换逻辑
function toggleProgramRows() {
  if (this.value === '0') {
    // 选中本科项目:显示本科行,隐藏硕士行
    bscRow.style.display = 'table-row';
    mscRow.style.display = 'none';
  } else {
    // 选中研究生项目:显示硕士行,隐藏本科行
    bscRow.style.display = 'none';
    mscRow.style.display = 'table-row';
  }
}

// 页面加载时设置初始状态(默认选中第一个选项)
window.addEventListener('DOMContentLoaded', function() {
  toggleProgramRows.call(progSelect);
});

// 绑定下拉框的change事件
progSelect.addEventListener('change', toggleProgramRows);

方案2:jQuery实现(适合已引入jQuery的项目)

如果你的项目已经使用jQuery,可以用更简洁的代码实现:

$(document).ready(function() {
  const $prog = $('#prog');
  const $msc = $('#msc');
  const $bsc = $('#bsc');

  // 切换逻辑
  function toggleRows() {
    if ($prog.val() === '0') {
      $bsc.show();
      $msc.hide();
    } else {
      $bsc.hide();
      $msc.show();
    }
  }

  // 初始状态设置
  toggleRows();
  // 绑定change事件
  $prog.on('change', toggleRows);
});

重要提示

你提供的HTML中有一个问题:两个<select>的id都是major,这违反了HTML中id必须唯一的规范,可能导致后续JS操作或样式设置出现异常。建议修改为唯一ID,比如:

<tr id="msc">
  <td>Masters : </td>
  <td>
     <select name="major" id="msc-major">
       <option>MSC</option>
       <option>MSC2</option>
     </select>
  </td>
</tr>
<tr id="bsc">
  <td>Bachelors : </td>
  <td>
    <select name="major" id="bsc-major">
       <option>BSC</option>
       <option>BSC2</option>
    </select>
  </td>
</tr>

内容的提问来源于stack exchange,提问作者Ashen Anushka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:23:19