jQuery 遍历 - eq() 方法

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

 

定义和用法

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

index:整数,指示元素的位置(最小为 0)。如果是负数,则从集合中的最后一个元素往回计数。

上面的例子调用的结果是为项目 3 设置了红色背景。请注意,index 是基于零的,并且是在 jQuery 对象中引用元素的位置,而不是在 DOM 树中

$('li').eq(2).css('background-color', 'red');

 

如果提供负数,则指示从集合结尾开始的位置,而不是从开头开始。

$('li').eq(-2).css('background-color', 'red');

 

如果无法根据指定的 index 参数找到元素,则该方法构造带有空集的 jQuery 对象,length 属性为 0

$('li').eq(5).css('background-color', 'red');

 



posted @ 2017-05-18 09:07  <一>  阅读(485)  评论(0编辑  收藏  举报