本文通過實例講解jQuery中 siblings() 方法的用法,供有需要的朋友參考。
此方法能夠獲取匹配元素集合中每一個元素的同輩(兄弟)元素,並可通過表達式對同輩元素集合進行篩選。
代碼如下:$(selector).siblings(expr)
參數說明:expr 為可選項,用於篩選同輩元素的表達式。
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.cnblogs.com/" />
<title>siblings()函數-博客園</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").siblings().css("color","red")
})
</script>
</head>
<body>
<div class="first">
<p>我是first下的p</p>
<span>我是div下的span</span>
</div>
<div class="second">
<ul>
<li>我是li</li>
</ul>
<p>我是second下的p</p>
</div>
</body>
</html>
該例中,$("p").siblings() 會選中每個 p 的所有同輩元素,並將其文字顏色設為紅色。
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.cnblogs.com/" />
<title>siblings()函數-博客園</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").siblings("span").css("color","red")
})
</script>
</head>
<body>
<div class="first">
<p>我是first下的p</p>
<span>我是div下的span</span>
</div>
<div class="second">
<ul>
<li>我是li</li>
</ul>
<p>我是second下的p</p>
</div>
</body>
</html>
這裡加上 "span" 表達式後,只有 p 元素中同輩為 span 的元素會被選中並變色,其餘同輩元素不受影響,體現了參數的篩選作用。
希望本文所述對大家的jQuery程序設計有所幫助。