是否有理由在'.class'上使用选择器'* .class'? [英] Is there any reason to use selector '*.class' over '.class'?

查看:80
本文介绍了是否有理由在'.class'上使用选择器'* .class'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中找到它,不知道在.class选择器上使用*.class选择器有什么意义.

解决方案

无论是在jQuery中还是没有意义(嘶嘶声)选择器上下文或CSS选择器上下文.在匹配的元素和特异性方面,*.class.class都是等效的.

*字符仅在单独用于指代任何元素时才有意义.这意味着您使用任何其他没有类型选择器的简单选择器. 即使这样,您也很少会发现自己需要将事件挂接到DOM或操纵DOM上每个元素的属性.

如果要使用类,伪类,ID等,那么没有通用选择器就没有意义了,因为无论如何都会对所选元素进行相应的过滤.

此外,这是*与其他选择器一起使用的缺点,引自 jQuery文档:

警告:全部或通用选择器非常慢,除非单独使用.

这是选择器规范所说的:

如果用*表示的通用选择器(即没有名称空间前缀)不是伪元素之后,则可以省略*并暗示通用选择器的存在.

示例:

  • *[hreflang|=en][hreflang|=en]是等效的,
  • *.warning.warning是等效的,
  • *#myid#myid是等效的.

I found it in code and don't know what's the point of using *.class selector over .class selector.

解决方案

There's no point to it, whether in the jQuery (Sizzle) selector context or CSS selector context. Both *.class and .class are equivalent in terms of elements matched, and specificity.

The * character is only significant when used by itself to refer to any element; it's implied the moment you use any other simple selector without a type selector. Even then, you will seldom, if ever, find yourself needing to hook events to or manipulate properties of every element on the DOM.

If you are going to use classes, pseudo-classes, IDs and so on, then there's no point having the universal selector there as the selected elements will be filtered accordingly anyway.

Furthermore, here's one shortcoming of using * with other selectors, quoted from the jQuery documentation:

Caution: The all, or universal, selector is extremely slow, except when used by itself.

And here's what the Selectors spec says:

If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

Examples:

  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • *.warning and .warning are equivalent,
  • *#myid and #myid are equivalent.

这篇关于是否有理由在'.class'上使用选择器'* .class'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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