2010-10-13 107 views
6

我有一個表,我與工作就像這樣:使用jQuery類添加到首個TD上的每個錶行

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tablecontent"> 
    <tr class="tablerow"> 
    <td>This is the td I want to add a class to.</td> 
    <td class="cell2">Stuff</td> 
    <td class="cell3">Stuff</td> 
    </tr> 
    <tr class="tablerow"> 
    <td>This is the td I want to add a class to.</td> 
    <td class="cell2">Stuff</td> 
    <td class="cell3">Stuff</td> 
    </tr> 
</table> 

每一行的第一個TD標記沒有一個類或ID跟...共事。我沒有權限更改HTML輸出,因此我想添加一些jQuery來定位每個表格的第一個TD標籤。我將如何做到這一點?

回答

11
$('#tablecontent td:first-child').addClass('someClass'); 

這使用the first-child selector以選擇#tablecontent表中的所有元素<td>是其母公司的first-child

例子:http://jsfiddle.net/duKKC/

+0

真棒。這工作完美。謝謝! – 2010-10-13 16:24:09

+0

@Robert - 不客氣。 :O) – user113716 2010-10-13 16:31:31

1

你可以試試下面的jQuery

$('.tablerow').each(function(index) { 
    $(this).children('td').first().addClass('class'); 
}); 

這將解決你的問題:)

0
$(".tablerow").find("td:first-child").addClass('class'); 
0

我相信以下將工作:

$('.tablerow td:first-child').addClass('class'); 
0
$('#tablecontent td:first-child').addClass("first-row"); 
相關問題