jQuery中children()和find()之间最快的是哪一个?
这个问题的答案哪一个是间最快children()和find()方法取决于使用情况。该find()方法遍历整个Dom,而该children()方法获取节点的直接子级。
jQuerychildren()方法
该children()方法是获取节点的直接子级。children([selector])方法获取一组元素,其中包含每个匹配元素集的所有唯一直接子代。
这是此方法使用的所有参数的描述-
选择器 -这是一个可选参数,用于过滤掉所有子项。如果未提供,则将选择所有子项。
示例
您可以尝试运行以下代码来学习如何使用jQuerychildren()方法:
<html>
<head>
<title>jQuery children() method</title>
<script src = "https://cdn.staticfile.org/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>jQueryfind()方法
该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://cdn.staticfile.org/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>