jQuery 遍歷兄弟節點
使用 jQuery,你可以輕鬆使用以下方法查詢元素的兄弟節點:next()、nextAll()、prev()、prevAll()、siblings() 等等。讓我們看看其中一些兄弟節點遍歷−
next() 方法
next() 方法用於返回所選元素的下一個兄弟元素。讓我們看一個示例−
示例
<!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(){ $("h3").next().css({"color": "gray", "border": "3px dashed blue"}); }); </script> </head> <body class="demo"> <div> parent <h1>sibling</h1> <h2>sibling</h2> <h3>sibling</h3> <h4>sibling</h4> </div> </body> </html>
輸出
這將產生以下輸出−
prev() 方法
prev() 方法用於返回所選元素的前一個兄弟元素。讓我們看一個示例−
示例
<!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(){ $("h3").prev().css({"color": "gray", "border": "3px dashed blue"}); }); </script> </head> <body class="demo"> <div> parent <h1>sibling</h1> <h2>sibling</h2> <h3>sibling</h3> <h4>sibling</h4> </div> </body> </html>
輸出
這將產生以下輸出−
siblings() 方法
siblings() 方法用於返回所選元素的所有兄弟元素。讓我們看一個示例−
示例
<!DOCTYPE html> <html> <head> <style> div { width:600px; } .demo * { display: block; border: 2px solid orange; color: blue; padding: 10px; margin: 10px; } </style> <script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("h3").siblings().css({"color": "gray", "border": "3px dashed blue"}); }); </script> </head> <body class="demo"> <div> parent <h1>sibling</h1> <h2>sibling</h2> <h3>sibling</h3> <h4>sibling</h4> </div> </body> </html>
輸出
這將產生以下輸出−
廣告