您的位置:首页 > Web前端 > JQuery

jQuery 遍历 中 eq() 方法

2017-09-28 14:37 281 查看
在写js的时候很多情况下都需要遍历,jquery中提供了eq()的方法。

1、通过为 index 为 2 的 div 添加适当的类,将其变为蓝色:

$("body").find("div").eq(2).addClass("blue");

示例:

<!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>


2、为项目 3 设置了红色背景。请注意,index 是基于零的,并且是在 jQuery 对象中引用元素的位置,而不是在 DOM 树中。
$('li').eq(2).css('background-color', 'red');

示例:

<!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>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

<script>$('li').eq(2).css('background-color', 'red');</script>
</body>
</html>

3、如果提供负数,则指示从集合结尾开始的位置,而不是从开头开始,倒数第二个背景色变成红色
$('li').eq(-2).css('background-color', 'red');

示例:

<!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>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

<script>$('li').eq(-2).css('background-color', 'red');</script>
</body>
</html>

4、如果无法根据指定的 index 参数找到元素,则该方法构造带有空集的 jQuery 对象,length 属性为 0
$('li').eq(5).css('background-color', 'red');

这里,没有列表项会变为红色,这是因为 .eq(5) 指示的第六个列表项。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery 遍历 javascript