jquery获取元素的索引_如何在jQuery中获取具有特定索引的元素

jquery获取元素的索引

In this post, we are going to discuss how to get an element with a specific index. jQuery API provides eq() method for this operation.

在本文中,我们将讨论如何获取具有特定索引的元素。 jQuery API为此操作提供了eq()方法。

jQuery eq()方法 (jQuery eq() method)

The jQuery eq() method is used to get an element with a specific index of the selected HTML element. You can give either positive or negative integer value as index. The index of the first element of the matched element is 0. If we use selector.eq(-1), it will return the last element and selector.eq(0) will return the first element in the matched set of elements.

jQuery eq()方法用于获取具有选定HTML元素的特定索引的元素。 您可以指定正整数或负整数作为索引。 匹配元素的第一个元素的索引为0。如果我们使用selector.eq(-1),它将返回最后一个元素,而selector.eq(0)将返回匹配的元素集中的第一个元素。

Here is the general syntax for using jQuery eq() method:

这是使用jQuery eq()方法的一般语法:

  • selector.eq(index)

    选择器.eq(索引)

index could be any positive or negative integer.

index可以是任何正整数或负整数。

jQuery eq()示例 (jQuery eq() example)

Following example demonstrates the jQuery eq() method usage.

以下示例演示了jQuery eq()方法的用法。

<!doctype html>
<html>
<head>
<title>jQuery Traversing eq</title>
<style>
    .highlight{
       background: yellow;
     }

    .highlight1{
       background: green;
     }
  
    div{
      display: block;
      border: 3px solid black;
      color: black;
      padding: 5px;
      margin: 25px;
      width:250px;
     }
</style>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<h2>jQuery eq() demo</h2>
 
<div>My index is 0, also -6 from last</div>
<div>My index is 1, also -5 from last</div>
<div>My index is 2, also -4 from last</div>
<div>My index is 3, also -3 from last</div>
<div>My index is 4, also -2 from last</div>
<div>My index is 5, also -1 from last</div>

 
<script>
$( "div" ).eq( "1" ).addClass("highlight");
$( "div" ).eq( "-6" ).addClass("highlight1");

</script>
</body>
</html>

In this example, we can see the use of jQuery eq() method. The $("div").eq(1) will return the second div element and changes the color to yellow. Similarly the elements are searched when index is negative, so -6 will return the first div element in this html page. Below image shows the output produced by above HTML page.

在此示例中,我们可以看到jQuery eq()方法的使用。 $("div").eq(1)将返回第二个div元素,并将颜色更改为黄色。 同样,当index为负时将搜索元素,因此-6将返回此html页面中的第一个div元素。 下图显示了以上HTML页面产生的输出。

That’s all for now. We will discuss some more traversing techniques in the coming posts.

目前为止就这样了。 我们将在以后的文章中讨论更多的遍历技术。

翻译自: https://www.journaldev.com/5339/how-to-get-an-element-with-specific-index-jquery

jquery获取元素的索引

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值