:jQuery / Sizzle中的nth-of-type()?
令我感到惊讶的是, Sizzle (jQuery使用的选择器引擎)带有内置的:nth-child()
选择器,但缺少:nth-of-type()
选择器。
为了说明:nth-child()
和:nth-of-type()
之间的区别并说明问题,请考虑以下HTML文档 :
:nth-of-type() in Sizzle/jQuery? body p:nth-of-type(2n) { background: red; }The following CSS is applied to this document:
body p:nth-of-type(2n) { background: red; }This is paragraph #1.
This is paragraph #2. (Should be matched.)
This is paragraph #3.
This is paragraph #4. (Should be matched.)
This is not a paragraph, but adiv
.This is paragraph #5.
This is paragraph #6. (Should be matched.)
$(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'); });
由于Sizzle使用浏览器原生的
querySelector()
和querySelectorAll()
方法(如果存在这些方法querySelectorAll()
(即已经实现了Selectors API的浏览器 ),所以像$('body p:nth-child');
当然会工作。 但它在旧版浏览器中不起作用,因为Sizzle没有这个选择器的回退方法。是否可以轻松地将
:nth-of-type()
选择器添加到Sizzle,或者在jQuery中实现它(可能使用内置的:nth-child()
选择器 )? 带参数的自定义选择器会很好。/** * 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中检查或重命名选择器 )
你当然可以添加偶数和奇数 :
match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];
jQuery插件moreSelectors支持nth-of-type(以及许多其他选择器)。 我建议使用它,或者只是实现一个只实现你需要的精确选择器的简单插件。 您应该能够从那里复制粘贴代码。
快乐的黑客!
我不能假装知道如何实现nth-of-type,但jQuery确实提供了一种机制,您可以通过它创建自己的自定义选择器。
以下问题涉及自定义选择器,可能会为您提供有用的见解
您编写了哪些有用的自定义jQuery选择器?