2011-12-05 86 views
2

在jQuery中,如何選擇內部只有2個TD的所有TR? 這裏的樣本:在表格內選擇TD

<table> 
    <tr> 
     <td></td> 
    </tr>   
    <tr> /* I only want to select this. */ 
     <td></td> 
     <td></td> 
    </tr> 
    <tr> 
     <td></td> 
    </tr> 
</table> 
+1

你的意思是 「至少2''​​」 或 「正好2''​​」? –

+0

爲什麼不像表中的類那樣使用更快的東西來確定你可能需要的東西? (我假設你生成的數據當然是) – Jakub

+0

@Jakub:或許Eron不能控制如何生成HTML,也許它來自第三方庫(客戶端或服務器端),外部web服務,... –

回答

0

使用長度命令。我想出了這個,你可能需要稍作修改。

$("table").find("tr").each(function() { 
    len = $(this).find("td").length; 
    if(len == 2) { 
     //do stuff 
    } 
}); 

http://api.jquery.com/length/

+1

我想你的意思是'$(this).find(「td」).length' –

+0

我做到了。感謝您的領導:) – Aventuris

2

至少兩

$('tr > td:nth-child(2)').parent(); 
  • 如果有一個td:nth-child(2),那麼顯然有至少兩個td小號

對於正好有兩個

$('tr > td:nth-child(2):last-child').parent(); 
  • 如果有一個tr > td:nth-child(2):last-child,那麼第二td也是最後td,所以必須有隻有兩個。

或者這樣:

$('tr').has('td:nth-child(2)'); // at least two 

$('tr').has('td:nth-child(2):last-child'); // exactly two 
+0

我很高興你不是一個10K的用戶 - 如果你是,你將能夠看到我愚蠢的答案 - 讓我們只是說eq沒有做我以爲它做了什麼: - /幸運的是,我很快刪除了它 –

+0

@AdamRackis:是的,我有一些那裏。 – RightSaidFred