jQuery&#39; s:last-child& quot;选择器不会尊重< body& gt;作为Jsbin的父母? [英] jQuery&#39;s &quot;:last-child&quot; selector won&#39;t respect &lt;body&gt; as parent on Jsbin?
问题描述
我有这个简单的HTML:
I have this simple HTML :
<body>
<a>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</a>
</body>
div是<a>
的子级.
来自 jQuery :
:last-child Selector
-选择作为最后一个子元素的所有元素 他们的父母.
:last-child Selector
— Selects all elements that are the last child of their parent.
好, 运行此代码:
$("div:last-child" ).css('background-color','red')
将产生:
好,我们删除<a>
,以便divs
将成为Body
Ok , let's remove <a>
so that divs
will be direct children of the Body
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</body>
结果:什么都没画. ( http://jsbin.com/kamepu/4 )
问题
那些divs
是Body
的子级.为什么它不起作用?
Those divs
are children of Body
. why it is not working ?
NB我知道我可以使用last
.但这不是我的问题.
NB I know I can use last
. but that's not my question.
推荐答案
如果您查看DOM,则JS Bin在结束</body>
标记之前插入一些script
元素,这可以防止任何div
出现匹配div:last-child
.请记住,尽管通常不渲染script
元素,但它们确实像其他HTML元素一样存在于DOM中,因此会影响选择器匹配.
If you look at the DOM, JS Bin inserts some script
elements before the closing </body>
tag, which prevents any of the div
s from matching div:last-child
. Remember that although script
elements are (usually) not rendered, they do exist in the DOM just like any other HTML element, and as a result will affect selector matching.
最后一个div
实际上是其类型的最后一个,即使它不是body
的最后一个子代;您可以通过切换到:last-of-type
进行验证,它会匹配.
The last div
is in fact the last of its type, even if it isn't the very last child of body
; you can verify this by switching to :last-of-type
and it will match.
如评论中所述,堆栈片段也可以做到这一点:
As mentioned in the comments, Stack Snippets does this as well:
div:last-child { text-decoration: underline; }
div:last-of-type { color: red; }
<body>
<div>Red but no underline</div>
</body>
这篇关于jQuery&#39; s:last-child& quot;选择器不会尊重< body& gt;作为Jsbin的父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!