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

如何将下拉框选中值赋值到当前表格行的指定单元格

问题原因

  • 原代码中currentrow函数内的this默认指向全局window对象,无法匹配到触发事件的下拉框元素
  • $(this).closest('tr')返回的是jQuery封装的行DOM对象,不是行索引值,不能直接传入rows[]中作为下标使用

修复方案

步骤1:修改行内事件传参

将下拉框的onchange事件修改为同时传入选中值和元素本身:

onchange="currentrow(this.value, this)"

步骤2:修改JS函数逻辑

直接通过传入的元素定位到当前行,再修改对应单元格内容,原生JS即可实现,不需要依赖jQuery:

function currentrow(number, selectEl) {
  selectEl.closest('tr').cells[1].innerHTML = number;
}

完整可运行代码

<table id="mytable">
  <tr>
    <td>
      <select name="column()" onchange="currentrow(this.value, this)">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3" selected>3</option>
      </select>
    </td>
    <td>
      3
    </td>
  </tr>
  <tr>
    <td>
      <select name="column()" onchange="currentrow(this.value, this)">
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
      </select>
    </td>
    <td>
      2
    </td>
  </tr>
</table>
<script>
function currentrow(number, selectEl) {
  selectEl.closest('tr').cells[1].innerHTML = number;
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:48:01