: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的實現(xiàn):nth-child(n)是嚴格來自CSS規(guī)范,n值是“1索引”,也就是說,從1開始計數(shù)。對于所有其他選擇器表達式,但是,jQuery遵循JavaScript的“0索引”的計數(shù)。因此,給定一個單一<ul>包含兩個<li>, $('li:nth-child(1)')選擇第一個<li>,而$('li:eq(1)')選擇第二個。
:nth-child(n)偽類很容易混淆:eq(n),即使兩個可能導(dǎo)致完全不同的匹配的元素。用:nth-child(n) ,所有子元素都計算在內(nèi),不管它們是什么,并且指定的元素被選中僅匹配連接到偽類選擇器。而:eq(n)只有類選擇附加到偽類計算在內(nèi),不限于任何其他元素的孩子,而且第(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>