:nth-child() Selector
nth-child selector
version added: 1.1.4jQuery(':nth-child(index/even/odd/equation)')
- index
- 每个相匹配子元素的所引值,从
1
开始,也可以是字符串even
或odd
,或一个方程式( 例如:nth-child(even)
,:nth-child(4n)
)。
Description: 选择其父元素下的第N个子或奇偶元素。
因为jQuery的实现:nth-child(n)
是严格来自CSS规范,n
值是“1索引”,也就是说,从1开始计数。对于所有其他选择器表达式,但是,jQuery遵循JavaScript的“0索引”的计数。因此,给定一个单一<ul>
包含两个<li>
, $('li:nth-child(1)')
选择第一个<li>
,而$('li:eq(1)')
选择第二个。
:nth-child(n)
伪类很容易混淆:eq(n)
,即使两个可能导致完全不同的匹配的元素。用:nth-child(n)
,所有子元素都计算在内,不管它们是什么,并且指定的元素被选中仅匹配连接到伪类选择器。而:eq(n)
只有类选择附加到伪类计算在内,不限于任何其他元素的孩子,而且第(n +1)个一(n是基于0)被选中。
这个不寻常的用法,可进一步讨论中找到 W3C CSS specification.
Examples:
Example: Finds the second li in each matched ul and notes it.
<!DOCTYPE html>
<html>
<head>
<style>
div { float:left; }
span { color:blue; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div><ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
</ul></div>
<div><ul>
<li>Sam</li>
</ul></div>
<div><ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul></div>
<script>$("ul li:nth-child(2)").append("<span> - 2nd!</span>");</script>
</body>
</html>
Demo:
Example: This is a playground to see how the selector works with different strings. Notice that this is different from the :even and :odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so...
<!DOCTYPE html>
<html>
<head>
<style>
button { display:block; font-size:12px; width:100px; }
div { float:left; margin:10px; font-size:10px;
border:1px solid black; }
span { color:blue; font-size:18px; }
#inner { color:red; }
td { width:50px; text-align:center; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div>
<button>:nth-child(even)</button>
<button>:nth-child(odd)</button>
<button>:nth-child(3n)</button>
<button>:nth-child(2)</button>
</div>
<div>
<button>:nth-child(3n+1)</button>
<button>:nth-child(3n+2)</button>
<button>:even</button>
<button>:odd</button>
</div>
<div><table>
<tr><td>John</td></tr>
<tr><td>Karl</td></tr>
<tr><td>Brandon</td></tr>
<tr><td>Benjamin</td></tr>
</table></div>
<div><table>
<tr><td>Sam</td></tr>
</table></div>
<div><table>
<tr><td>Glen</td></tr>
<tr><td>Tane</td></tr>
<tr><td>Ralph</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
<tr><td>Dan</td></tr>
</table></div>
<span>
tr<span id="inner"></span>
</span>
<script>
$("button").click(function () {
var str = $(this).text();
$("tr").css("background", "white");
$("tr" + str).css("background", "#ff0000");
$("#inner").text(str);
});
</script>
</body>
</html>