jquery的这个this.find(":not(:has(:first))")什么意思?

发布于 2022-09-01 07:04:59 字数 220 浏览 22 评论 0

看一个网站js代码,无意间发现这个jquery选择器:

this.find(":not(:has(:first))").each(function() {
                . . . . . .
            });

这个(":not(:has(:first))")是什么意思?
如果改成通俗易懂点的形式,应该怎么来改?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

送你一个梦 2022-09-08 07:04:59

既然有答案提到了first-child伪类,为了不给题主误导,我查了文档:
https://api.jquery.com/first-selector/
https://api.jquery.com/first-child-selector/

这两个选择器是有区别的,
:first选择器,描述:Selects the first matched element.,意思就是选择第一个匹配的元素。
如,

<table>
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
</table>

<script>
$( "tr:first" ).css( "font-style", "italic" );
</script>

那么Row 1应用样式之后就变成了斜体了。(题中并不是标签:first,或者类:first的形式);

:first-child选择器,描述:Selects all elements that are the first child of their parent.,意思就是选择所有父元素的第一个子元素,(不是父元素的所有第一子元素,这么说是没有意义的)。
如,

<div>
  <span>John,</span>
  <span>Karl,</span>
  <span>Brandon</span>
</div>
<div>
  <span>Glen,</span>
  <span>Tane,</span>
  <span>Ralph</span>
</div>

<script>
$( "div span:first-child" )
  .css( "text-decoration", "underline" );

这样JohnGlen都会加上下划线了。


啰嗦了一段,就看下题目

this.find(":not(:has(:first))").each(function() {
                . . . . . .
});

如果把DOM结构当做一棵树的话,那么这句话的意思就是查找所有叶子节点,然后遍历做点什么。
:first前面没有标签也没有类,可以当做*:first的形式来看。
如果是:not(:has(:first-child))我相信结果也是一样的,毕竟叶子节点是没有第一个子元素的。

改成通俗易懂的我不会。 但是,可以看下公子的评论。

break-down的工作不写代码的码农同学已经做了。

风渺 2022-09-08 07:04:59

:has(:first)用于获取子元素中运用:first伪类的父元素
:not(selector)则用于排除和selector匹配的元素

:not(:has(:first))就是用于排除那些子元素中运用:first伪类的父元素

补充一个demo:demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文