为什么这个第 n 个子元素返回一个意外的元素?
html & jQuery 位于下面,它也位于 http://www.jsfiddle.net/4fWUU。我期待得到 'wrapper' 的第二个子元素,即 id 为 'parent2' 的 div。然而返回的 id 是我不期望的“child1_1_1_2”。
我可以使用 $o1.children()[1]
获得正确的 div,但我想知道为什么 nth-child 无法正常工作。
有什么想法吗?
<div id="wrapper">
<div id="parent1">
<div id="child1">
<div id="child1_1">
<div id="child1_1_1">
<div id="child1_1_1_1">
</div>
<div id="child1_1_1_2">
</div>
</div>
<div id="child1_1_2">
</div>
</div>
<div id="child1_2">
<div id="child1_2_1">
</div>
</div>
</div>
</div>
<div id="parent2">
</div>
</div>
var $o1 = $("#wrapper");
var id = $("div:nth-child(2)",$o1).attr("id");
alert(id);
The html & jQuery is below and it's also at http://www.jsfiddle.net/4fWUU. I am expecting to get the second child of 'wrapper' which is the div with id 'parent2'. However the returned id is 'child1_1_1_2' which I don't expect.
I can get the proper div using $o1.children()[1]
but I wanted to know why nth-child is not working right.
Any ideas why?
<div id="wrapper">
<div id="parent1">
<div id="child1">
<div id="child1_1">
<div id="child1_1_1">
<div id="child1_1_1_1">
</div>
<div id="child1_1_1_2">
</div>
</div>
<div id="child1_1_2">
</div>
</div>
<div id="child1_2">
<div id="child1_2_1">
</div>
</div>
</div>
</div>
<div id="parent2">
</div>
</div>
var $o1 = $("#wrapper");
var id = $("div:nth-child(2)",$o1).attr("id");
alert(id);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按上下文搜索与
.find()
相同,它在向上 DOM 树之前首先选取最深的后代。:nth-child()
如果您不指定父元素,则不关心父元素,因此每个其他元素包含的div
(是其子元素)#wrapper
或里面的任何内容都会被选中。.children()
方法,正如它上面所说的那样,将选择限制为元素的子元素,因此任何匹配的内容都将始终是子元素。使用它,但传递:nth-child()
选择器,如下所示:或者按照 Nick Craver 的建议,使用子选择器
>
将上下文搜索限制为#wrapper:Searching by context is the same as
.find()
, which picks up the deepest descendants first before traveling up the DOM tree.:nth-child()
does not care about the parent if you don't specify a parent, thus everydiv
that's contained by (is a child of) some other element of#wrapper
or anything inside gets selected.The
.children()
method, as it says on the tin, limits the selection to your element's children, so anything matched will always be a child. Use that instead but pass the:nth-child()
selector like so:Or as Nick Craver suggests, use the child selector
>
to limit your contextual search to children of#wrapper
:该选择器实际上有 4 个实例:
there are actually 4 instances of that selector: