今天总结一下jQuery中的子元素过滤
目录
:first-child Selector
描述:选择所有父级元素下的第一个子元素
语法:$(":first-child")或者jQuery(":first-child")
<div>
<p></p>
<span></span>
</div>
<script>
$(function(){
$("div:first-child") //<p></p>
})
</script>
:last-child Selector
描述:选择所有父级元素下的最后一个子元素
语法:$(":last-child")或者jQuery(":last-child")
<div>
<p></p>
</span></span>
</div>
<script>
$(function(){
$("div:last-child") //span
})
</script>
:first-of-type Selector
描述:选择所有相同元素中的第一个子元素
语法:$(":first-of-type")或者jQuery(":first-of-type")
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<script>
$(function(){
$(":first-of-type") //div1
})
</script>
:last-of-type Selector
描述:选择所有元素之间具有相同元素名称的最后一个元素
语法:$(":last-of-type")或者jQuery(":last-of-type")
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<script>
$(function(){
$(":last-of-type") //div4
})
</script>
:nth-child() Selector
描述:选择所指定规则的元素
语法:$(":nth-child(index/even/odd)")或者jQuery(":nth-child(index/even/odd)")
注意:括号中的index、even、odd是选择的规则,表示可以是索引,偶数索引,奇数索引
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
$(function(){
$(":nth-child(1)") //div1
$(":nth-child(even)") //div0 div2
$(":nth-child(odd)") //div1 div3
})
</script>