2012-02-24 88 views
0

我有一堆HTML TABLE標記,我試圖使用JQuery向下鑽取所有生成的TABLE中的特定TD單元。問題是我有JQuery獲取正確的TD單元,但它只獲得具有相同結構的一系列TABLE中的第一個單元。使用JQuery獲取一系列表中的特定TD

這裏是我使用的獲取到正確的TD JQuery的:

<script type="text/javascript"> 
    $(function ($) { 
     $(".dataContent div table tbody tr td").first().css("background", "yellow"); 
    }); 
</script> 

這裏是簡化了HTML結構:

<td class="dataContent"> 
    <a href="#"></a> 
    <div> 
     <table>...</table> 
     <div> 
      <table cellspacing="0" cellpadding="0" style="border-width:0;"> 
       <tbody> 
        <tr> 
         <td><a href="#"><img /></a></td><!--this cell--> 
         <td><div>random cell</div></td> 
        </tr> 
       </tbody> 
      </table> 
      <!--Generated Tables with same structure as the TABLE above--> 
      <table></table> 
      <table></table> 
      <table></table> 
      <table></table> 
     </div> 
    </div> 
</td> 

所以我不僅想要得到的第一個單元格在第一個TABLE中,但也在下面的所有生成的表中。任何幫助,將不勝感激。

回答

1

使用td:first-child而不是.first()獲得了在其列第一的每個表中的所有單元:

$(".dataContent div table tbody tr td:first-child").css("background", "yellow"); 

使用:first選擇或.first()方法導致的jQuery只返回第一個元素在匹配的所有元素中,所以它絕不會超出那一個單元格。

+0

Arrr!我知道這很容易,但是我錯過了這一點,我感到很蠢!謝謝你的幫助。 – crazymatt 2012-02-24 01:13:22

1

$(".dataContent div table").eq(0).find('td').eq(0)給你第一個表中的第一個TD。

$(".dataContent div table").length會給你表的數量。

做一個循環。簡單。

+0

感謝發佈,其他答案是一個更容易的修復。 – crazymatt 2012-02-24 01:14:13