在 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.com/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.com/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>
廣告