JQuery在表行中向tds添加编号

Dan*_*der 4 javascript jquery function

我已经想出了这个函数来为我表中的表行中的元素添加编号类:

$('tr td:contains(".")').each(function(i){
     $(this).addClass("reportcellno-" + i);
});
Run Code Online (Sandbox Code Playgroud)

基本上在这里,我正在搜索任何带小数点的表格单元格,我想在每一行中进行交互并添加类reportcellno-1,reportcellno-2

这很好用,我整天都在玩它.唯一的问题是编号一直在继续,而不是按行限制.

我从上面输出的HTML代码是:

<tr>
<td class="reportcellno-1">10.1</td>
<td class="reportcellno-2">5.7</td>
</tr>

<tr>
<td class="reportcellno-3">10.6</td>
<td class="reportcellno-4">10.9</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

虽然我实际上想要得到这个:

<tr>
<td class="reportcellno-1">10.1</td>
<td class="reportcellno-2">5.7</td>
</tr>

<tr>
<td class="reportcellno-1">10.6</td>
<td class="reportcellno-2">10.9</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

所以基本上对于每个表行,我想开始编号.我甚至不确定这是否可行.

And*_*ong 6

通过去tr代替:

$('tr').each(function() {
   $(this).children('td:contains(".")').each(function(i) {
      $(this).addClass("reportcellno-" + i);
   });
});
Run Code Online (Sandbox Code Playgroud)

编辑:循环方式较少,但可能性较差:

$('tr td:contains(".")').each(function(){
   $(this).addClass("reportcellno-" + (+$(this).index() + 1));
});?
Run Code Online (Sandbox Code Playgroud)

在这里,我们使用的事实是a td是a的子元素tr,并index()返回元素相对于其兄弟元素的位置.

来自文档:

如果没有将参数传递给.index()方法,则返回值是一个整数,指示jQuery对象中第一个元素相对于其兄弟元素的位置.