jQuery' s:last-child& quot;选择器不会尊重< body& gt;作为Jsbin的父母? [英] jQuery's ":last-child" selector won't respect <body> as parent on Jsbin?

查看:134
本文介绍了jQuery' s:last-child& quot;选择器不会尊重< body& gt;作为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 )

问题

那些divsBody的子级.为什么它不起作用?

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 divs 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&amp;#39; s:last-child&amp; quot;选择器不会尊重&lt; body&amp; gt;作为Jsbin的父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆