看一个网站js代码,无意间发现这个jquery选择器:
this.find(":not(:has(:first))").each(function() {
. . . . . .
});
这个(":not(:has(:first))")是什么意思?
如果改成通俗易懂点的形式,应该怎么来改?
:has(:first)用于获取子元素中运用:first伪类的父元素
:not(selector)则用于排除和selector匹配的元素
:not(:has(:first))就是用于排除那些子元素中运用:first伪类的父元素
补充一个demo:demo
既然有答案提到了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" );
这样John
和Glen
都会加上下划线了。
啰嗦了一段,就看下题目
this.find(":not(:has(:first))").each(function() {
. . . . . .
});
如果把DOM
结构当做一棵树的话,那么这句话的意思就是查找所有叶子节点,然后遍历做点什么。:first
前面没有标签也没有类,可以当做*:first
的形式来看。
如果是:not(:has(:first-child))
我相信结果也是一样的,毕竟叶子节点是没有第一个子元素的。
改成通俗易懂的我不会。 但是,可以看下公子
的评论。
break-down
的工作不写代码的码农
同学已经做了。