:nth-of-type() 选择器
nth-of-type selector
描述:选择所有这样的元素,它们是它们的父元素中的第n个子元素,相对于具有相同元素名的同辈元素。
加入于: 1.9
jQuery( ":nth-of-type(index/even/odd/equation)" )index: 每个要匹配的子元素的索引值,从1开始,也可以是字符串even或odd,或者是一个公式(例如:nth-of-type(even)、:nth-of-type(4n))。
因为:nth-选择器的jQuery编译器严格派生自CSS规范文档,所以n的值是基于1的索引,意味着计数从1开始。对于其它选择器表达式,比如说:eq()或:even,jQuery遵循JavaScript的“0起步索引”计数。
关于这种用法的进一步讨论,可在W3C CSS specification找到。
示例
查找每个<span>,这个<span>是 其所有同辈<span>元素中的第二个元素。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-of-type demo</title>
<style>
.nth {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
<span>John</span>,
<b>Kim</b>,
<span>Adam</span>,
<b>Rafael</b>,
<span>Oleg</span>
</div>
<div>
<b>Dave</b>,
<span>Ann</span>
</div>
<div>
<i><span>Maurice</span></i>,
<span>Richard</span>,
<span>Ralph</span>,
<span>Jason</span>
</div>
<script>
$( "span:nth-of-type(2)" )
.append( "<span> is 2nd sibling span</span>" )
.addClass( "nth" );
</script>
</body>
</html>
演示结果