令我感到惊讶的是Sizzle(jQuery使用的选择器引擎)带有内置:nth-child()
选择器,但缺少:nth-of-type()
选择器。
为了说明:nth-child()
和:nth-of-type()
之间的区别并说明问题,请考虑the following HTML document:
<!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中实现它(或许可以使用the built-in :nth-child()
selector)? custom selector with parameters会很好。
答案 0 :(得分:14)
/**
* Return true to include current element
* Return false to exclude current element
*/
$.expr[':']['nth-of-type'] = function(elem, i, match) {
if (match[3].indexOf("n") === -1) return i + 1 == match[3];
var parts = match[3].split("+");
return (i + 1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
};
Test case - (检入IE或重命名选择器)
您当然可以添加甚至&amp; 奇数:
match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];
答案 1 :(得分:4)
jQuery插件moreSelectors支持nth-of-type(以及许多其他选择器)。我建议使用它,或者只是实现一个只实现你需要的精确选择器的简单插件。您应该能够从那里复制粘贴代码。
快乐的黑客攻击!
答案 2 :(得分:1)
我不能假装知道如何实现nth-of-type,但jQuery确实提供了一种机制,您可以通过它创建自己的自定义选择器。
以下问题涉及自定义选择器,可能会为您提供有用的见解