令我惊讶的是,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会更好。
发布于 2010-01-23 00:21:47
jQuery插件moreSelectors支持第n种类型(以及许多其他选择器)。我建议要么使用它,要么简单地实现一个简单的插件,它只实现您需要的确切选择器。你应该能够从那里复制粘贴代码。
黑客快乐!
发布于 2010-01-19 21:29:26
我不能假装知道nth-of-type是如何实现的,但是jQuery确实提供了一种机制,您可以通过它创建自己的自定义选择器。
以下问题涉及自定义选择器,可能会为您提供有用的见解
https://stackoverflow.com/questions/2093355
复制相似问题