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

如何获取指定<tr>下<td>内下拉选择框的选中值?

如何获取指定表格行内下拉选择框的选中值?

先看你贴出来的HTML结构:

<tr class="table-info" id="tr1">
  <td>
    <select class="form-control">
      <option>foobar</option>
      <option>foobar2</option>
    </select>
  </td>
</tr>

你的JavaScript代码里有几个小问题,导致没法正确拿到选中值:

  • 你用tds_day[1]去取第二个td,但你的HTML里tr#tr1只有一个td,索引应该是0;而且这个td根本没设id,所以tds_day[1].id会是undefined,后面的jQuery选择器自然找不到元素。
  • 另外,closest('select')是找当前元素的祖先元素,但select是td的子元素,不是它的上层元素,这步逻辑搞反啦。

下面给你两种靠谱的解决方案:

方案一:原生JavaScript写法

// 先拿到目标表格行
const trDay = document.getElementById('tr1');
// 直接在该行里找到对应的select元素
const selectEle = trDay.querySelector('select.form-control');
// 获取选中的值和显示文本
const selectedValue = selectEle.value;
const selectedText = selectEle.options[selectEle.selectedIndex].text;

console.log('选中值:', selectedValue);
console.log('选中文本:', selectedText);

方案二:jQuery写法(更简洁)

如果你习惯用jQuery,代码可以更短:

// 直接定位到tr下的select,获取选中的文本和值
const selectedText = $('#tr1 select.form-control').find(':selected').text();
const selectedValue = $('#tr1 select.form-control').val();

console.log('选中文本:', selectedText);
console.log('选中值:', selectedValue);

两种方法都能准确拿到下拉框的选中内容,你可以根据自己的代码环境选合适的~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:10:04