令我惊讶的是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()
方法(如果存在)(即在已经实现Selectors API$('body p:nth-child');
的浏览器中),当然可以使用类似的东西。但它在旧版浏览器中不起作用,因为 Sizzle 没有此选择器的后备方法。
是否可以轻松地将:nth-of-type()
选择器添加到 Sizzle,或者在 jQuery 中实现它(也许通过使用内置的:nth-child()
选择器)?带有参数的自定义选择器会很好。