代码之家  ›  专栏  ›  技术社区  ›  Mathias Bynens

:jQuery/Sizzle中类型()的第n个?

  •  16
  • Mathias Bynens  · 技术社区  · 15 年前

    令我惊讶的是 Sizzle :nth-child() 选择器,但缺少 :nth-of-type() 选择器。

    来说明两者之间的区别 :n-child() :n-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对此选择器没有回退方法。

    是否可以轻松添加 选择Sizzle,或在jQuery中实现它(通过使用 the built-in :nth-child() selector (也许是吧?)?A. custom selector with parameters 那太好了。

    3 回复  |  直到 15 年前
        1
  •  14
  •   gblazex    14 年前
    /**
     * 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];
    

        2
  •  4
  •   Emil Stenström    15 年前

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

    快乐的黑客!

        3
  •  1
  •   Community CDub    8 年前

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

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

    What useful custom jQuery selectors have you written?