首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >:nth-of-type() in jQuery / Sizzle?

:nth-of-type() in jQuery / Sizzle?
EN

Stack Overflow用户
提问于 2010-01-19 20:20:38
回答 2查看 7.5K关注 0票数 16

令我惊讶的是,Sizzle ( jQuery使用的选择器引擎)提供了一个内置的:nth-child()选择器,但缺少:nth-of-type()选择器。

要说明:nth-child():nth-of-type()之间的区别并说明问题,请考虑the following HTML document

代码语言:javascript
复制
<!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会更好。

EN

回答 2

Stack Overflow用户

发布于 2010-01-23 00:21:47

jQuery插件moreSelectors支持第n种类型(以及许多其他选择器)。我建议要么使用它,要么简单地实现一个简单的插件,它只实现您需要的确切选择器。你应该能够从那里复制粘贴代码。

黑客快乐!

票数 4
EN

Stack Overflow用户

发布于 2010-01-19 21:29:26

我不能假装知道nth-of-type是如何实现的,但是jQuery确实提供了一种机制,您可以通过它创建自己的自定义选择器。

以下问题涉及自定义选择器,可能会为您提供有用的见解

What useful custom jQuery selectors have you written?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2093355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档