时间:2021-07-01 10:21:17 帮助过:5人阅读

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="imooc.css" rel="external nofollow" type="text/css">
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<h2>子元素筛选选择器</h2>
<h3>:first-child、:last-child、:only-child</h3>
<p class="left first-p">
<p class="p">
<a>:first-child</a>
<a>第二个元素</a>
<a>:last-child</a>
</p>
<p class="p">
<a>:first-child</a>
</p>
<p class="p">
<a>:first-child</a>
<a>第二个元素</a>
<a>:last-child</a>
</p>
</p>
<script type="text/javascript">
//查找class="first-p"下的第一个a元素
//针对所有父级下的第一个
$(".first-p a:first-child").css("color", "#CD00CD");
</script>
<script type="text/javascript">
//查找class="first-p"下的最后一个a元素
//针对所有父级下的最后一个
//如果只有一个元素的话,last也是第一个元素
$(".first-p a:last-child").css("color", "red");
</script>
<script type="text/javascript">
//查找class="first-p"下的只有一个子元素的a元素
$(".first-p a:only-child").css("color", "blue");
</script>
<h3>:nth-child、:nth-last-child</h3>
<p class="left last-p">
<p class="p">
<a>:first-child</a>
<a>第二个元素</a>
<a>第三个元素</a>
<a>:last-child</a>
</p>
<p class="p">
<a>:first-child</a>
<a>第二个元素</a>
</p>
<p class="p">
<a>:first-child</a>
<a>第二个元素</a>
<a>第三个元素</a>
<a>:last-child</a>
</p>
</p>
<script type="text/javascript">
//查找class="last-p"下的第二个a元素
$(".last-p a:nth-child(2)").css("color", "#CD00CD");
</script>
<script type="text/javascript">
//查找class="last-p"下的倒数第二个a元素
$(".last-p a:nth-last-child(2)").css("color", "red");
</script>
</body>
</html>相关推荐:
CSS的子元素选择器用法详细介绍
以上就是jQuery子元素选择器详解的详细内容,更多请关注Gxl网其它相关文章!