jQuery中的nth()偽類選擇器是什麼?
第n個偽類的定義是什麼?
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偽類選擇器.
這是ofollow,noindex" target="_blank"> Sizzle engine 中使用的一個鮮為人知的位置選擇器:
:nth:
Finds thenth
element on the page.
你會發現上面的定義 here in the Github documentation for Sizzle .
為什麼選擇不同的元素:nth-child()/:nth-of-type()?
nth()和您的其他選擇器選擇不同元素的原因是因為nth()是一個基於零的索引選擇器,而CSS選擇器是基於1的索引選擇器.
這是可以理解的,這可能會令人困惑,因為大多數人會假設nth()將保持與類似命名的CSS偽類選擇器(例如nth-child()和nth-type-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.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/17382703/what-is-the-nth-pseudo-class-selector-in-jquery