令我惊讶的是,
Sizzle(jQuery使用的选择器引擎)带有一个内置的:nth-child()选择器,但缺少:nth-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会很好
解决方法
/** * 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或重新命名选择器)
你当然可以加上奇怪的:
match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];