jQuery 遍历 - 后代
向下遍历 DOM
children()
find()
children() 方法
children() 方法返回被选元素的所有直接子元素(仅儿子辈)。
参数可选,添加参数表示通过选择器进行过滤,对元素进行筛选。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.descendants *
{
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").children("p.1").css({"color":"blue","border":"5px solid green"});
});
</script>
</head>
<body>
<div class="descendants" style="width:300px;">
<p class="1">p (儿子元素)
<span>span (孙子元素)</span>
</p>
<p class="2">p (儿子元素)
<span>span (孙子元素)</span>
</p>
</div>
</body>
</html>返回类名为 "1" 的所有 <p> 元素,并且它们是 <div> 的直接子元素
find() 方法
find() 方法返回被选元素的后代元素,一路向下直到最后一个后代。
参数是必选的,可以为选择器、jQuery对象可元素来对元素进行筛选。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.descendants *
{
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("span").css({"color":"red","border":"3px solid blue"});
});
</script>
</head>
<body>
<div class="descendants" style="width:300px;">
<p>p (儿子元素)
<span>span (孙子元素)</span>
</p>
<p>p (儿子元素)
<span>span (孙子元素)</span>
</p>
</div>
</body>
</html>返回属于 <div> 后代的所有 <span> 元素。

女神的闺蜜爱上我
血崩。。。
8年前 添加回复 0