:nth-of-type() 在 jQuery/Sizzle 中? [英] :nth-of-type() in jQuery / Sizzle?
问题描述
令我惊讶的是 Sizzle(jQuery 使用的选择器引擎)带有一个内置的 :nth-child()
选择器,但缺少 :nth-of-type()
选择器.
It surprised me that Sizzle (the selector engine jQuery uses) comes with a built-in :nth-child()
selector, but lacks an :nth-of-type()
selector.
为了说明 :nth-child()
和 :nth-of-type()
之间的区别并说明问题,请考虑 以下 HTML 文档:
To illustrate the difference between :nth-child()
and :nth-of-type()
and to illustrate the problem, consider 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 没有此选择器的后备方法.
Since Sizzle uses the browser-native querySelector()
and querySelectorAll()
methods if those are present (i.e. in browsers that already implement the Selectors API), stuff like $('body p:nth-child');
will of course work. It won’t work in older browsers though, because Sizzle has no fallback method for this selector.
是否可以轻松地将 :nth-of-type()
选择器添加到 Sizzle,或者在 jQuery 中实现它(通过使用 可能是内置的 :nth-child()
选择器)?带参数的自定义选择器不错.
Is it possible to easily add the :nth-of-type()
selector to Sizzle, or to implement it in jQuery (by using the built-in :nth-child()
selector, perhaps)? A custom selector with parameters would be nice.
推荐答案
/**
* 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;
};
测试用例 -(签入 IE 或重命名选择器)
您当然也可以添加偶数&奇数:
You can of course add even & odd too:
match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];
这篇关于:nth-of-type() 在 jQuery/Sizzle 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!