2011-08-29 69 views
1

我在我的文檔中有一個表,它可能包含或不包含多個嵌套表。每個表(包括外部和可能的內部)都包含tbody標籤。我想匹配最外面的tbody標籤。追加到選擇器匹配的最外層元素

下面是一個示例文檔:

<table id="shippingContainer"> 
    <thead> 
    </thead> 
    <tbody> 
     <tr> 
      <td> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <table> 
        <tbody> 
        </tbody> 
       </table> 
      </td> 
     </tr> 
</table> 

在這種情況下我有JQuery的選擇器選擇一個最外層的表。我想選擇與該表關聯的tbody元素,但不選擇嵌套表內的任何tbody元素。

我最初的選擇是簡單的:

$("#shippingContainer").find("tbody"); 

而且這並不明顯的原因工作。謝謝您的幫助!

回答

5

可以使用child selector以實現:

$("#shippingContainer > tbody"); 

這將<tbody>元素是你的表的直接子匹配。

+0

這真的很酷!我不知道這個選擇器。謝謝您的幫助。 – BlackSheep

0

您可以到如下使用子選擇器,:

這會在你的shippingContainer表中選擇第一tbody元素:

//This will select the first tbody element (of your main table) 
$("#shippingContainer > tbody") 

這將選擇嵌套tbody元素在您的主表內:

//This will select the tbody element within the table (the inner table) 
$("#shippingContainer").find('table > tbody') 

Read more on child selectors here

+0

這就是我的意思 - 我不是說這兩個看起來相當。 :) –

+0

一旦我讀得更仔細一點,並意識到你的意圖,我就刪除了我的評論。感謝您澄清它。 – Dennis

0

你也可以這樣做:

$("#shippingContainer").find("tbody").first();