jQuery:如何获取选择数组中元素的索引

jQuery: how to get the index of an element in the selection array?

本文关键字:数组 选择 元素 索引 获取 何获取 jQuery      更新时间:2023-09-26

我有一个这样的HTML结构:

<div class="container">
  <div class="item">
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
  </div>
  <div class="item">
    <a href="#">4</a>
    <a href="#">5</a>
    <a href="#">6</a>
  </div>
</div>

我用jQuery选择了所有的A-s,在这里总共得到了6个对象。我想在 6 的数组中获取 A 的索引(例如,我可以检测单击了哪个 A),但是当我使用 .index() 时,我获取元素相对于其父元素的索引。因此,对于第 5 个 A,我得到的索引与第 2 个相同,因为第 5 个实际上是其div.item 中其组中的第二个:

$('a').click(function(){
    console.log ( $(this).index() ); // returns "1" for the 5th A
});

那么有没有办法在选择的数组中获取单击元素的索引,而不是在 DOM 中的父元素中获取索引?

您可以将单击的元素传递给 index 方法:

var $a = $('.container > .item > a').click(function() {
    console.log ( $a.index(this) ); 
});
看看

.index() 的 jquery 文档。您可以按如下方式修改代码以获得所需的结果:

$('.container').on("click", "a", function(){
    console.log ( $("a").index($(this))); 
});

$('a').click(function(){
  $("#result").text($('a').toArray().indexOf(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="item">
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
  </div>
  <div class="item">
    <a href="#">4</a>
    <a href="#">5</a>
    <a href="#">6</a>
  </div>
</div>
<div id="result"></div>