16

Sizzle (jQuery が使用するセレクター エンジン) には組み込みの:nth-child()セレクターが付属しているのに、セレクターがないことに驚きました:nth-of-type()

:nth-child()ととの違い:nth-of-type()を説明して問題を説明するために、次の HTML ドキュメントを考えてみましょう。

<!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()メソッドが存在する場合 (つまり、セレクター APIを既に実装しているブラウザー内)にそれらを使用するため$('body p:nth-child');、もちろん動作します。ただし、Sizzle にはこのセレクターのフォールバック メソッドがないため、古いブラウザーでは機能しません。

:nth-of-type()セレクターを Sizzleに簡単に追加したり、jQuery に実装したりすることは可能ですか (おそらく組み込みの:nth-child()selectorを使用して)? パラメータ付きのカスタムセレクターがいいでしょう。

4

3 に答える 3

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;
};

テスト ケース- ( IE をチェックインするか、セレクターの名前を変更します)

もちろん、偶数奇数も追加できます。

match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];

</p>

于 2011-01-21T16:58:12.723 に答える
4

jQuery プラグインmoreSelectorsは、nth-of-type (および他の多くのセレクター) をサポートしています。それを使用するか、必要なセレクターのみを実装する単純なプラグインを実装することをお勧めします。そこからコードをコピーして貼り付けることができるはずです。

ハッピーハッキング!

于 2010-01-22T16:21:46.560 に答える
1

nth-of-type がどのように実装されているかはわかりませんが、jQuery には、独自のカスタム セレクターを作成できるメカニズムが用意されています。

次の質問はカスタム セレクターを扱っており、有益な洞察を提供する可能性があります。

作成した便利なカスタム jQuery セレクターは何ですか?

于 2010-01-19T13:29:25.757 に答える