jQuery 中 jQuery.children( ) 和 jQuery.siblings( ) 有什麼區別?
jQuery children() 方法
children( [selector] ) 方法獲取一組元素,其中包含與匹配元素集中的每個元素的獨特直接子元素。
下面是此方法所用所有引數的說明 −
- selector − 這是篩選所有子元素的可選引數。如果沒有提供,則會選擇所有子元素。
示例
您可以嘗試執行以下程式碼,以瞭解如何使用 jQuery children() 方法
<html> <head> <title>jQuery children() method</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/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 siblings() 方法
如果您想獲取同級元素,可以使用 jQuery siblings() 方法。它返回選定元素的所有同級元素。
示例
您可以嘗試執行以下程式碼,以瞭解如何在 jQuery 中使用 siblings() 方法
<!DOCTYPE html> <html> <head> <style> .myclass * { display: block; border: 2px solid green; color: green; padding: 3px; margin: 10px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("li.new").siblings().css({"color": "blue", "border": "4px solid blue"}); }); </script> </head> <body> <div style="width:600px;" class="myclass"> <ol>ol <li>li</li> <li>li</li> <li class="new">li- This is the sibling.</li> <li>li</li> <li>li</li> </ol> </div> </body> </html>
廣告