jquery - 按顺序排列简单选择器

标签 jquery css jquery-selectors css-selectors

这只是一个概念性问题,涉及良好实践。


问题很简单。是否有任何“正确”的方式来订购 jQuery/CSS 选择器的各个部分?例如,假设我有一个具有以下属性的元素:

<div class="red green blue" id="someDiv" anAttr="something">

为了更好的衡量,让我们在它悬停时也瞄准它。


下面的选择器有什么区别吗?:

div.red.green.blue#someDiv[anAttr='something']:hover
div#someDiv.red.green.blue[anAttr='something']:hover
div.red#someDiv[anAttr='something']:hover.blue.green
div[anAttr='something'].blue:hover#someDiv.red.green

意思是,目标的顺序真的重要吗?或者我可以按我想要的任何顺序排列它们吗?

根据这个JSFiddle , 它们在技术上都有效。

最佳答案

5.2 Selector syntax

A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order. The simple selector matches if all of its components match.

Note: the terminology used here in CSS 2.1 is different from what is used in CSS3. For example, a "simple selector" refers to a smaller part of a selector in CSS3 than in CSS 2.1. See the CSS3 Selectors module [CSS3SEL].

A selector is a chain of one or more simple selectors separated by combinators. Combinators are: white space, ">", and "+". White space may appear between a combinator and the simple selectors around it.

The elements of the document tree that match a selector are called subjects of the selector. A selector consisting of a single simple selector matches any element satisfying its requirements. Prepending a simple selector and combinator to a chain imposes additional matching constraints, so the subjects of a selector are always a subset of the elements matching the last simple selector.

One pseudo-element may be appended to the last simple selector in a chain, in which case the style information applies to a subpart of each subject.

发件人:w3.org

关于jquery - 按顺序排列简单选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27557387/

相关文章:

HTML - 如何围绕动态内容设置固定菜单

jquery - 需要帮助选择 jQuery 选择器

jquery - 此 jQuery/HTML 代码中的性能/可访问性问题?

javascript - WordPress 和 jquery

javascript - 框架的可用性问题是什么?

javascript - 如何在Jquery或Phonegap跨平台中获取IP地址

jquery - 单击关闭按钮后,如何删除警告框的基于 FontAwesome 的背景?

javascript - header 和主体未对齐绘制的 Jquery.DataTable

jquery - 为什么这个带句点的 jquery 选择器不起作用

jquery - 有没有一个 jquery 解决方案可以通过显示文本从选择下拉列表中删除项目