jquery nth
jQuery nth-child 选择器
jQuery 的 :nth-child() 选择器用于匹配父元素下的第 n 个子元素。语法如下:
$("parentSelector :nth-child(n)")
其中 n 可以是数字、关键词(如 even 或 odd)或公式(如 2n+1)。
常见用法示例
选择第 3 个子元素:
$("ul li:nth-child(3)").css("color", "red");
选择所有偶数位置的子元素:
$("ul li:nth-child(even)").css("background-color", "#eee");
使用公式选择每第 3 个元素:
$("ul li:nth-child(3n)").css("font-weight", "bold");
与 :eq() 的区别
:nth-child() 是基于 DOM 位置的选择器,而 :eq() 是基于 jQuery 对象集合的索引。
// 选择 DOM 中第 2 个 li 元素
$("ul li:nth-child(2)");
// 选择 jQuery 集合中索引为 1 的 li 元素
$("ul li").eq(1);
注意事项
:nth-child() 是从 1 开始计数的,不是从 0 开始。公式中的 n 从 0 开始计算,但结果是从 1 开始应用。

浏览器兼容性
所有现代浏览器都支持 :nth-child() 选择器,包括 IE9 及以上版本。






