从具有特定tds数量的表中选择所有trs

时间:2011-09-06 08:02:09

标签: jquery jquery-selectors

我有桌子

<table>
 <tr>
  <td colspan="3"></td>
 </tr>
 <tr> //select this
  <td></td>
  <td></td>
  <td></td>
 </tr>
 <tr> //select this
   <td></td>
   <td></td>
   <td></td>
 </tr>
</table>

因此,对于上表,我想选择包含3个tds

的所有trs

我怎么能用jquery做到这一点?

基本上我需要得到这些行的数量。

3 个答案:

答案 0 :(得分:5)

您可以使用.filter() [docs]

$('table tr').filter(function(){
    return $(this).children('td').length === 3;
});

注意: @mu's answer更简洁,在现代浏览器中效果更佳。我仍然会将此答案作为.filter()的一般演示。

答案 1 :(得分:2)

您可以在每个<td>中选择第三个<tr>并跳过一个级别来获取父级:

$('tr td:nth-child(3)').parent();

在这种情况下使用:nth-child是安全的,因为您的<tr>应该只有<td>个孩子。

例如:

h = $('<table><tr colspan="3"><td></td></tr><tr id="x"><td><span>x</span></td><td></td><td></td></tr><tr id="y"><td></td><td></td><td></td></tr></table>');
trs = h.find('tr td:nth-child(3)').parent();
// trs[0] is <tr id="x">
// trs[1] is <tr id="y">

由Felix Kling提供的演示(现在jsfiddle.net重新开始):http://jsfiddle.net/6kMTE

答案 2 :(得分:1)

您可以使用:

$('tr:has(td:eq(2))')

选择位置3中包含tr的任何td(js从零开始)。

注意您的HTML无效 - colspan属于td,而非tr