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

如何基于列标题为表格行内的radio按钮添加checked属性(jQuery实现)

解决方法:用jQuery为指定列的Radio按钮添加checked属性

很简单,咱们可以通过定位目标表头的位置,再找到对应列的Radio按钮来实现需求,下面分两种常见场景给出实现代码:

场景1:仅选中第二行(数据行第一行)的对应Radio

// 先定位到标题为"MyHeader2"的表头,获取它的列索引(从0开始计数)
const targetColumnIndex = $('th:contains("MyHeader2")').index();

// 找到对应列的Radio按钮,设置选中状态
$('table tr:eq(1) td:eq(' + targetColumnIndex + ') input[type="radio"]').prop('checked', true);

代码解释:

  • $('th:contains("MyHeader2")'):精准匹配文本内容为MyHeader2的表头单元格
  • .index():获取该表头在所在行的列位置索引,方便后续定位对应数据列
  • $('table tr:eq(1)'):选中表格里的第二行(因为第一行是表头,jQuery索引从0开始)
  • td:eq(' + targetColumnIndex + '):定位到该行对应表头列的单元格
  • .prop('checked', true):给找到的Radio按钮设置选中状态(这里用prop而非attr,因为checked是DOM元素的固有属性,prop更适合操作这类属性)

场景2:选中所有数据行的对应Radio

如果你的表格有多行数据,想要给每一行的MyHeader2列Radio都加选中状态,可以这样写:

const targetColumnIndex = $('th:contains("MyHeader2")').index();
// 选中所有非表头行的对应列Radio
$('table tr:not(:first) td:eq(' + targetColumnIndex + ') input[type="radio"]').prop('checked', true);

代码解释:

  • tr:not(:first):排除表头行,选中所有数据行,这样就能批量处理所有行的对应Radio按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:17:48