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

如何通过Jquery为HTML表格行动态添加data-row-num属性值

为HTML表格行添加data-row-num属性的解决方案

你的代码存在两个问题:一是循环中每次都给所有<tr>设置属性,导致最终所有行的属性值一致;二是没有正确利用循环索引生成递增的行号。以下是修正后的实现:

修正后的完整代码

<table id="example" class="table table-striped first-table" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
        </tr>
        <tr>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
        </tr>
    </tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
   $('#example').dataTable({});

   // 仅遍历tbody中的行,避免给表头行添加属性
   $('#example tbody tr').each(function(index) {
       // index从0开始,所以行号要加1
       $(this).attr("data-row-num", index + 1); 
   }); 
});
</script>

关键说明

  • 用$('#example tbody tr')精准定位表格主体的行,不会影响表头的<tr>元素
  • jQuery的each()方法会传入索引值(从0开始计数),通过index + 1得到从1开始的行号
  • 使用$(this)指代当前正在遍历的行,确保每个行的属性值独立设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:50:19