这只是一个概念性问题,涉及良好实践。
问题很简单。是否有任何“正确”的方式来订购 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/