2011-08-29 71 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();