我很惊讶Sizzle(jQuery使用的选择器引擎)带有内置的:nth-child()
选择器,但缺少:nth-of-type()
选择器。
为了说明:nth-child()
和:nth-of-type()
之间的区别并说明问题,请考虑以下HTML文档:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>:nth-of-type() in Sizzle/jQuery?</title>
<style>
body p:nth-of-type(2n) { background: red; }
</style>
</head>
<body>
<p>The following CSS is applied to this document:</p>
<pre>body p:nth-of-type(2n) { background: red; }</pre>
<p>This is paragraph #1.</p>
<p>This is paragraph #2. (Should be matched.)</p>
<p>This is paragraph #3.</p>
<p>This is paragraph #4. (Should be matched.)</p>
<div>This is not a paragraph, but a <code>div</code>.</div>
<p>This is paragraph #5.</p>
<p>This is paragraph #6. (Should be matched.)</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
// The following should give every second paragraph (those that had red backgrounds already after the CSS was applied) an orange background.
// $('body p:nth-of-type(2n)').css('background', 'orange');
});
</script>
</body>
</html>
由于Sizzle使用浏览器本地的
querySelector()
和querySelectorAll()
方法(如果在已实现选择器API的浏览器中存在),因此像$('body p:nth-child');
这样的东西当然可以工作。但是在旧版浏览器中无法工作,因为Sizzle没有此选择器的回退方法。是否可以轻松地将
:nth-of-type()
选择器添加到Sizzle中,或者在jQuery中实现它(例如通过使用内置的:nth-child()
选择器)?带有参数的自定义选择器会很好。
$('p:even')
不是已经给你想要的结果了吗?你已经有了选择器 (p
),所以你只需要过滤它即可。 - Kobip:nth-child(2n)
会匹配每个父元素中的每个第二个段落。如果有两个 DIV,都包含三个段落,则以下段落(按 DOM 顺序)将被p:nth-child(2n)
匹配:#2、#5。明白了吗?这不仅仅是获取文档中的每个P
,然后将其过滤为每个 mnth 元素。 是的,$('p:even')
是$('p:nth-child(2n)')
的别名,但不是$('p:nth-of-type(2n)')
的别名。此外,在此示例中我使用了2n
,但当然也应该有其他变化。 - Mathias Bynens:nth-of-type()
选择器,但Firefox的querySelectorAll()
知道。这就是为什么它“起作用”的原因,但这并不是由于Sizzle。如果在Sizzle中加入这个功能,那么它将在所有浏览器中都能够工作,这将是很好的。 - Mathias Bynens