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

如何通过行ID和th名称/索引用jQuery或原生JS替换td元素文本?

解决表格单元格修改问题

当前表格数据

<tr id="1">
<th>Name</th>
<td>John</td>
<th>Country</th>
<td>US</td>
</tr>

尝试的代码

let rowID = 1;
let columnTitle = "Country";
$('#'+rowID+' td:eq('+columnTitle+')').html("Japan");

期望结果

<tr id="1">
<th>Name</th>
<td>John</td>
<th>Country</th>
<td>Japan</td>
</tr>

问题原因与修复代码

你原来的代码逻辑错误:td:eq()选择器需要传入数字索引,但你传的是字符串"Country",导致找不到目标单元格。

修复方案1(快速匹配)

用:contains定位对应标题的<th>,再取它后面的<td>修改内容:

let rowID = 1;
let columnTitle = "Country";
$('#' + rowID + ' th:contains("' + columnTitle + '")').next('td').html("Japan");

修复方案2(精确匹配)

如果担心有多个<th>包含目标文本,用filter精确匹配文本内容,更可靠:

let rowID = 1;
let columnTitle = "Country";
$('#' + rowID + ' th').filter(function() {
  return $(this).text().trim() === columnTitle;
}).next('td').html("Japan");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:32:39