×
目录
[1]通用形式 [2]首尾元素 [3]唯一元素前面的话
在上一篇中已经介绍过基础选择器和层级选择器,本文开始介绍过滤选择器。过滤选择器是jQuery选择器中最为庞大也是最为出彩的一部分。以CSS结构伪类选择器为基础,jQuery过滤选择器增加了很多扩展功能。本文先从与CSS选择器最相近的子元素过滤选择器开始说起
通用形式
$(':nth-child(index)')
$(':nth-child(index)')选择每个父元素的第index个子元素(index从1算起),返回集合元素
$(':nth-child(1)') 每个父元素下第1个子元素 $('span:nth-child(1)') 每个父元素下第1个子元素,且该子元素为span元素 $('div span:nth-child(1)') 每个为div元素的父元素下第1个子元素,且该子元素为span元素
<button id="btn1" style="color: red;">$(':nth-child(1)')button><button id="btn2" style="color: blue;">$('span:nth-child(1)')button><button id="btn3" style="color: green;">$('div span:nth-child(1)')button><button id="reset">还原button><div id="t1"><i>1.1i><span>1.2span>div><p id="t2"><span>2.1span><i>2.2i>p><div id="t3"><span>3.1span><i>3.2i>div><script src="jquery-3.1.0.js">script><script>reset.onclick =function(){history.go();} //匹配每个父元素的第1个子元素,结果是1.1、2.1和3.1//[注意]实际上,元素作为元素的第1个子元素,也被设置为color:redbtn1.onclick =function(){$(':nth-child(1)').css('color','red');} //匹配每个父元素的第1个子元素,且该子元素是span元素,结果是2.1和3.1btn2.onclick =function(){$('span:nth-child(1)').css('color','blue');} //匹配每个为div元素的父元素的第1个子元素,且该子元素是span元素,结果是3.1btn3.onclick =function(){$('div span:nth-child(1)').css('color','green');} script>
对应于CSS的结构伪类选择器nth-child(n)