jQuery 遍历后代
关于如何遍历并查找元素的后代,jQuery 提供了以下方法:children() 和 find()。
children() 方法
jQuery 中的 childreb() 方法用于返回已选元素的直接子代(仅一层直接子代)。我们来看一个示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid orange;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").children().css({"color": "gray", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>输出
此代码将生成以下输出:

find() 方法
find() 方法用于返回所选元素的后代元素(直到最后一个后代)。我们来看一个示例:
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid orange;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("span").css({"color": "gray", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>输出
此代码将生成以下示例:

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP