循环通过tr's,并在jquery中通过索引转义特定的tr

loop through a set of tr's and escape a specific tr by index in jquery

本文关键字:tr 索引 转义 jquery 循环 并在      更新时间:2023-09-26

hi我想循环通过一些类似的tr。

<tr>
 <td> <input type="radio" id="r11"   value="a" name="r1_selectedobjects" /> </td>
   <td><input type="radio" id="r12"   value="b" name="r1_selectedobjects" /> <td>
</tr>
<tr>
   <td><input type="radio" id="r21"   value="a" name="r2_selectedobjects" /></td>
  <input type="radio" id="r22"   value="b" name="r2_selectedobjects" /></td>
</tr>
   <td><input type="radio" id="r31"   value="a" name="r3_selectedobjects" /></td>
   <td><input type="radio" id="r32"   value="b" name="r3_selectedobjects" /></td>
<tr>
<tr>
<td><input type="submit" id="matbutton" data-inline="true"  value="Submit" onclick="return CheckMatrixRadio(this);" /></td>
    </tr>

我可以用$('tr').each(function(){});

我想跳过3 rd tr

这个

</tr>
   <td><input type="radio" id="r31"   value="a" name="r3_selectedobjects" /></td>
   <td><input type="radio" id="r32"   value="b" name="r3_selectedobjects" /></td>
<tr>

如何做到这一点。我想我不知道任何calss或id名称,我只知道tr的索引,在这种情况下,3

如何在我的each循环中跳过那个tr。请帮忙。。。。。。。。。。。

each回调接收一个从零开始的索引,告诉您正在查看哪个匹配的项目,因此:

$('tr').each(function(index){
    // If not the third one...
    if (index !== 2) {
        // ...do something
    }
});

如果出于任何原因,您不想使用each(您在问题中提到了它,但只是涵盖了基础),而是想创建一个包含除第三行之外的所有行的jQuery实例,我知道最有效的方法是:

var rows = $('tr');
rows = rows.not(rows[2]);

其经由CCD_ 8从匹配集合移除第三行。您也可以使用包含:not:eq:的选择器来实现相同的功能

$('tr:not(:eq(2))')

但是您需要jQuery来处理选择器,而不是允许它将选择器传递给浏览器的querySelectorAll实现(如果它有)。*

三种的示例


(旁注:如果页面上的任何位置都有不相关的tr,您可能需要使选择器更具体地针对您正在查看的行组。)


*PiTheNumber在他的回答中指出$('tr:not(:nth-child(3))')也应该这样做。这很有用,因为它的优点是:not:nth-child都可以由浏览器本地处理。请注意,:nth-child使用基于1的索引,并且:eq非常不同—它检查元素是其容器的哪个子元素,而不是它是否是第n个匹配的元素。如果tr元素都在同一个tbody中,则应该适用于具有这些元素的表。

您可以使用:nth-child()选择器跳过第三个tr

$('tr:not(:nth-child(3))').each(function(index, value) {
});

使用索引,它是循环当前迭代的基于0的索引。

例如

$('tr').each(function(index){
    if(index !== 2) {
      // Do stuff here for rows that aren't the 3rd one
    }
});

请参阅http://api.jquery.com/each/有关更多信息,

首先看一下您的标记!这里面有一个很大的错误。关闭你的<tr>标签。我帮你更正了

<tr>
   <td> <input type="radio" id="r11"   value="a" name="r1_selectedobjects" /> </td>
   <td><input type="radio" id="r12"   value="b" name="r1_selectedobjects" /> <td>
</tr>
<tr>
   <td><input type="radio" id="r21"   value="a" name="r2_selectedobjects" /></td>
   <input type="radio" id="r22"   value="b" name="r2_selectedobjects" /></td>
</tr>
<tr>
   <td><input type="radio" id="r31"   value="a" name="r3_selectedobjects" /></td>
   <td><input type="radio" id="r32"   value="b" name="r3_selectedobjects" /></td>
</tr>
<tr>
   <td><input type="submit" id="matbutton" data-inline="true"  value="Submit" onclick="return CheckMatrixRadio(this);" /></td>
</tr>

然后您可以排除jQuery中给定的元素:

$('tr:not(:nth-child(3)').each(function(){ // function });

$('tr').not(':nth-child(3)')将为您提供结果。