jQuery選擇器之子元素篩選選擇器
子元素篩選選擇器不常使用,其篩選規(guī)則比起其它的選擇器稍微要復(fù)雜點(diǎn)
子元素篩選選擇器描述表:

注意事項(xiàng):
- :first只匹配一個(gè)單獨(dú)的元素,但是:first-child選擇器可以匹配多個(gè):即為每個(gè)父級(jí)元素匹配第一個(gè)子元素。這相當(dāng)于:nth-child(1)
- :last 只匹配一個(gè)單獨(dú)的元素, :last-child 選擇器可以匹配多個(gè)元素:即,為每個(gè)父級(jí)元素匹配最后一個(gè)子元素
- 如果子元素只有一個(gè)的話,:first-child與:last-child是同一個(gè)
- :only-child匹配某個(gè)元素是父元素中唯一的子元素,就是說當(dāng)前子元素是父元素中唯一的元素,則匹配
- jQuery實(shí)現(xiàn):nth-child(n)是嚴(yán)格來(lái)自CSS規(guī)范,所以n值是“索引”,也就是說,從1開始計(jì)數(shù),:nth-child(index)從1開始的,而eq(index)是從0開始的
- nth-child(n) 與 :nth-last-child(n) 的區(qū)別前者是從前往后計(jì)算,后者從后往前計(jì)算
任務(wù)
在代碼編輯器中第33行填寫相應(yīng)代碼
$('.first-div a:first-child')
在代碼編輯器中第40行填寫相應(yīng)代碼
$('.first-div a:last-child')
在代碼編輯器中第45行填寫相應(yīng)代碼
$('.first-div a:only-child')
在代碼編輯器中第71行填寫相應(yīng)代碼
$('.last-div a:nth-child(2)')
在代碼編輯器中第76行填寫相應(yīng)代碼
$('.last-div a:nth-last-child(2)')
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="imooc.css" type="text/css">
<script src="http://idcbgp.cn/static/lib/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<h2>子元素篩選選擇器</h2>
<h3>:first-child、:last-child、:only-child</h3>
<div class="left first-div">
<div class="div">
<a>:first-child</a>
<a>第二個(gè)元素</a>
<a>:last-child</a>
</div>
<div class="div">
<a>:first-child</a>
</div>
<div class="div">
<a>:first-child</a>
<a>第二個(gè)元素</a>
<a>:last-child</a>
</div>
</div>
<script type="text/javascript">
//查找class="first-div"下的第一個(gè)a元素
//針對(duì)所有父級(jí)下的第一個(gè)
?.css("color", "#CD00CD");
</script>
<script type="text/javascript">
//查找class="first-div"下的最后一個(gè)a元素
//針對(duì)所有父級(jí)下的最后一個(gè)
//如果只有一個(gè)元素的話,last也是第一個(gè)元素
?.css("color", "red");
</script>
<script type="text/javascript">
//查找class="first-div"下的只有一個(gè)子元素的a元素
?.css("color", "blue");
</script>
<h3>:nth-child、:nth-last-child</h3>
<div class="left last-div">
<div class="div">
<a>:first-child</a>
<a>第二個(gè)元素</a>
<a>第三個(gè)元素</a>
<a>:last-child</a>
</div>
<div class="div">
<a>:first-child</a>
<a>第二個(gè)元素</a>
</div>
<div class="div">
<a>:first-child</a>
<a>第二個(gè)元素</a>
<a>第三個(gè)元素</a>
<a>:last-child</a>
</div>
</div>
<script type="text/javascript">
//查找class="last-div"下的第二個(gè)a元素
?.css("color", "#CD00CD");
</script>
<script type="text/javascript">
//查找class="last-div"下的倒數(shù)第二個(gè)a元素
?.css("color", "red");
</script>
</body>
</html>
.left {
width: auto;
height: 120px;
}
.left div {
width: 150px;
height: 100px;
padding: 5px;
margin: 5px;
float: left;
background: #bbffaa;
border: 1px solid #ccc;
}
a{
display: block;
}
請(qǐng)驗(yàn)證,完成請(qǐng)求
由于請(qǐng)求次數(shù)過多,請(qǐng)先驗(yàn)證,完成再次請(qǐng)求