jQuery 遍历 - eq() 和siblings() 方法

时间:2024-10-13 15:04:32

eq() 方法将匹配元素集缩减值指定 index 上的一个。

通过为 index 为 2 的 div 加入适当的类。将其变为蓝色:

<!DOCTYPE html>
<html>
<head>
<style>
div { width:60px; height:60px; margin:10px; float:left;
border:2px solid blue; }
.blue { background:blue; }
</style>
<script type="text/javascript" src="/jquery/jquery.js"></script>
</head> <body>
<div></div>
<div></div>
<div></div> <div></div>
<div></div>
<div></div> <script>$("body").find("div").eq(2).addClass("blue");</script>
</body>
</html>

siblings()查找每一个 p 元素的全部类名为 "selected" 的全部同胞元素:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
</head> <body>
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p> <script>
$("p").siblings(".selected").css("background", "yellow");
</script> </body>
</html>