我有这个简单的 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
— Selects all elements that are the last child of their parent.
然而,当running this code in JSBin:
$("div:last-child" ).css('background-color','red')
它产生了这个渲染输出:
即使我们删除 <a>
这样divs
将是 <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>
的 child ,那么为什么它不起作用?
最佳答案
如果您查看 DOM,JS Bin 会插入一些 script
收盘前的要素 </body>
标签,它可以防止任何 div
s 来自匹配 div:last-child
.请记住,尽管 script
元素(通常)不会呈现,它们确实像任何其他 HTML 元素一样存在于 DOM 中,因此会影响选择器匹配。
最后div
实际上是其类型的最后一个,即使它不是 body
的最后一个子节点;您可以通过切换到 :last-of-type
来验证这一点它将匹配。
如评论中所述,Stack Snippets 也这样做:
div:last-child { text-decoration: underline; }
div:last-of-type { color: red; }
<body>
<div>Red but no underline</div>
</body>
关于html - 当 <body> 是父级时,为什么 ":last-child"选择器不适用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088957/