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.com/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.com/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>
輸出
此程式碼將生成以下示例:
廣告