jquery - :nth() pseudo-class selector in jQuery?是什么

标签 jquery jquery-selectors

:nth 伪类的定义是什么?

我找不到任何关于它的 jQuery 或 CSS 文档,但它似乎存在:

var $list = $('<ul><li>1</li><li>2</li><li>3</li></ul>');

$list.find('li:nth(2)').text();

返回:“3”

同时:

 $list.find('li:nth-of-type(2)').text();
 $list.find('li:nth-child(2)').text();

两者都返回“2”

这个伪类是什么?有人可以向我指出一些有关它的文档吗?

最佳答案

什么是 :nth() 选择器?

与其他答案相反,:nth() 不是 CSS 伪类选择器。

这是一个鲜为人知的位置选择器,用于Sizzle engine :

:nth: Finds the nth element on the page.

你会发现上面的定义here in the Github documentation for Sizzle .

为什么它选择不同的元素来:nth-child()/:nth-of-type()?

nth() 和其他选择器选择不同元素的原因是 nth() 是一个从零开始的索引选择器,而 CSS 选择器是基于一个的索引选择器。

这是可以理解的,因为大多数人会认为 nth() 会与类似名称的 CSS 伪类选择器(例如 nth-child())保持某种一致性nth-of-type() - 然而,正如前面提到的,它们实际上并不相关。

那么,:nth() 的功能实际上更接近于 :eq() 吗?

是的。事实上,看起来好像 nth() is exactly the same as eq() :

Expr.pseudos["nth"] = Expr.pseudos["eq"];

This old mailing list conversation (2007) 暗示 John Resig 计划删除 :nth() 选择器,因为:

"I've searched the groups but I can't seem to find any related talk on this. What, if any, is the difference between using :eq(n) and :nth(n)? I'd like to know before I start standardizing on one or the other. Thanks." - Matt Penner

"They're the same, so you can use whichever you prefer. From jquery.js: nth: "m[3]-0==i", eq: "m[3]-0==i"" - Karl Swedberg

"Huh... I should probably nuke :nth()." - John Resig

但是,正如您所注意到的,:nth() 选择器的删除从未实现(无论如何,截至 2013 年)。

用法示例:

HTML:

<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>

jQuery:

$('p:nth(2)').text(); // Returns 3 as zero-based index.
$('p:eq(2)').text(); // Returns 3 as zero-based index.
$('p:nth-child(2)').text(); // Returns 2 as one-based index.
$('p:nth-of-type(2)').text(); // Returns 2 as one-based index.

jsFiddle version here.

关于jquery - :nth() pseudo-class selector in jQuery?是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382703/

相关文章:

javascript - jQuery 无法获得顶级父级?

多个线程上的 JavaScript setInterval

jquery - Highcharts 回流不适用于类选择器

jquery - 向使用 :contains 选择的元素添加类

php - 使用 AJAX 从表单发送图像

c# - 传递实体,从 View 到 Controller

javascript - 在特定元素/类上使用 lastModified

javascript - jQuery 克隆链接和包装/追加/替换?

javascript - jQuery - 当 id 是数组类型表示法时,ID 选择器需要帮助

jquery - 如果我已经引用了某个项目,则在 jQuery 中选择后代