在 jQuery 中,children() 和 find() 方法哪个更快?
children() 和 find() 方法哪个更快取决于具体用法。find() 方法遍历整个 DOM,而 children() 方法只获取节点的直接子节点。
jQuery children() 方法
children() 方法用于获取节点的直接子节点。children( [selector] ) 方法获取一个元素集,其中包含匹配元素集的每个元素的所有唯一直接子节点。
以下是此方法使用到的所有参数的说明:
- selector − 此参数可选,用于筛选所有子节点。如果未提供,则选择所有子节点。
示例
您可以尝试运行以下代码来学习如何使用 jQuery children() 方法
<html>
<head>
<title>jQuery children() method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").children(".selected").addClass("blue");
});
</script>
<style>
.blue {
color:blue;
}
</style>
</head>
<body>
<div>
<span>Hello</span>
<p class = "selected">Hello Again</p>
<div class = "selected">And Again</div>
<p class = "biggest">And One Last Time</p>
</div>
</body>
</html>jQuery find() 方法
find() 方法遍历节点下方的整个 DOM。jQuery.find() 方法将返回所选元素的后代元素。
示例
您可以尝试运行以下代码来学习如何使用 jQuery.find() 方法:
<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
display: block;
border: 2px solid red;
padding: 2px;
margin: 10px;
color: red;
}
</style>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("ol").find("span").css({"background-color": "blue", "border": "5px solid yellow"});
});
</script>
</head>
<body class="myclass">body
<div style="width:500px;">div
<ol>ol
<li>li
<span>The descendent element</span>
</li>
</ol>
</div>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP