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

标签 jquery jquery-selectors css-selectors selectors-api

令我惊讶的是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那就太好了。

最佳答案

/**
 * 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];

关于jquery - :nth-of-type() in jQuery/Sizzle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2093355/

相关文章:

javascript - 单击链接时将颜色更改为#fff

javascript - 使用 AJAX 和 jQuery 填充 div

javascript - 在 javascript 中从 Wordpress REST API 正确设置数组

javascript - 使用jquery更改图标

javascript - 带有 "." "_"的 Jquery 选择器不起作用

javascript - jQuery css 选择器匹配表单数组名称

jquery 选择器 - 选择每个表行内的第二个跨度子级

jQuery 在追加时自动关闭标签?例如$("<p/>")

javascript - 使用 css 选择器和 javascript 断言随按钮单击而更改的文本

css - 选择 css 中的第一个 dl 元素