jQuery 遍历 中 eq() 方法

来源:互联网 发布:和服羽织淘宝 编辑:程序博客网 时间:2024/05/16 13:49

在写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) 指示的第六个列表项。

原创粉丝点击