2013-11-28 37 views
0

我有以下(簡化)表結構:選擇表格行的更好方法?

<table class="form-table"> 
<tbody> 
<tr> 
<tr><--Need to select and add class on this guy based on h3 class "check"--> 
<th scope="row"> 
<h3 class="check">Default Checbox:</h3> 
</th> 
<td> 
</tr> 
</tbody> 
</table> 

所以我要選擇「錶行」的H3類「檢查」上面。表格是動態生成的,所以我不能只使用:eq(),:gt():lt()

要選擇這個傢伙我使用此代碼:

$('tbody tr').find('h3.check').parent().addClass('cool'); 
$('.cool').parent().addClass('until'); 

但問題是,我爲了做出選擇放棄不必要的類「酷」。

<table class="form-table"> 
<tbody>  
<tr> 
<tr> 
<tr class="until"><--Class successfully added but..--> 
<th class="cool" scope="row"><--An extra Class in order to select "table row"--> 
<h3 class="check">Default Checbox:</h3> 
</th> 
<td> 
</tr> 
</tbody> 
</table> 

有沒有更好的方法來做到這一點(不添加不必要的類)?

回答

2

您可以使用.has()

$('tbody tr').has('h3.check').addClass('cool'); 

:has

$('tbody tr:(h3.check)').addClass('cool'); 
+0

@PedroEstrada打字它 –

+0

謝謝你,我知道這是一些簡單的:=)你已經讓我很快樂。謝謝。 –

+0

「tbody」選擇器是多餘的,因爲每個TR都是TBODY的子節點(無論標記是否包含在標記中)。 – RobG

相關問題