gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:58:20 25 4
gpt4 key购买 nike

令我惊讶的是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com