jQuery 遍历 - 同胞(siblings)
同胞拥有相同的父元素
有以下方法在DOM树种水平遍历:
1.siblings()
2.next()
3.nextAll()
4.nextUntil()
1.siblings() | silblings()方法返回被选元素的所有同胞元素 |
2.next() | next() 方法返回被选元素的下一个同胞元素 |
3.nextAll() | nextAll() 方法返回被选元素的所有跟随的同胞元素 |
4.nextUntil() | nextUntil() 方法返回介于两个给定参数之间的所有跟随的同胞元素 |
5.prev() | 与next()方法类似 |
6.prevAll() | 与nextAll()方法类似 |
7.prevUntil() | 与nextUntil()方法类似 |
实例:
<script>
$(function(){
$(".btn1").click(function(){
$("h1").siblings().css({"color":"red","border":"2px solid red"});
});
$(".btn2").click(function(){
$("h1").siblings("p").css({"color":"red","border":"2px solid red"});
});
$(".btn3").click(function(){
$("h1").next().css({"color":"red","border":"2px solid red"});
});
$(".btn4").click(function(){
$("h1").nextUntil("h3").css({"color":"red","border":"2px solid red"});
});
});
</script>
</head>
<style type="text/css">
.d1 *{
display: block;
border: 1px solid blue;
padding: 10px;
margin: 5px;
}
</style>
<body>
<div class="d1" style="width: 500px">
<h1 class="h1">h1</h1>
<h2 class="h2">h2</h2>
<p class="p1">p1</p>
<p class="p2">p2</p>
<span>span</span>
<h3>h3</h3>
</div>
<button class="btn1">使用siblings遍历h1的同胞</button><br><br>
<button class="btn2">使用siblings遍历所有元素名是P的h1的同胞</button><br><br>
<button class="btn3">使用next遍历h1的下一个同胞</button><br><br>
<button class="btn4">使用nextUtil遍历h1到h3之间的同胞</button><br>
</body>