獲取方法:1、用siblings()獲取指定元素的兄弟元素,語法“指定元素.siblings()”,會返回一個包含所有兄弟元素的jQuery對象;2、用length屬性統(tǒng)計并返回jQuery對象中元素的個數(shù),語法“指定對象.length”。
本教程操作環(huán)境:windows7系統(tǒng)、jquery1.10.2版本、Dell G3電腦。
jquery求兄弟元素的個數(shù)的方法
1、使用siblings()方法獲取被選元素的所有兄弟元素
該方法沿著 DOM 元素的同級元素向前和向后遍歷。
指定元素.siblings()
會返回一個包含所有兄弟元素的jQuery對象。
2、使用length屬性獲取個數(shù)
length屬性會統(tǒng)計 jQuery 對象中元素的數(shù)目并返回。
指定對象.length
實現(xiàn)示例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .siblings,.siblings *{ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("h2").siblings().css("border","2px solid red") var len=$("h2").siblings().length; console.log("兄弟元素的個數(shù)為:"+len); }); }); </script> </head> <body> <div class="siblings">div (父) <p>p(兄弟元素)</p> <span>span(兄弟元素)</span> <h2>h2(本元素)</h2> <h3>h3(兄弟元素)</h3> <p>p(兄弟元素)</p> </div> <button>獲取兄弟元素的個數(shù)</button> </body> </html>
【推薦學(xué)習(xí):jQuery視頻教程、web前端視頻】