最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: how to get the index of an element in the selection array? - Stack Overflow

programmeradmin10浏览0评论

I have an HTML structure like this:

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

I select all the A-s with jQuery, and get a total of 6 objects here. I want to get the index of the A in the array of 6 (so I can detect which A has been clicked, for example), but when I use .index() I get the index of the element relative to its parent. So for the 5th A I get the same index as for the 2nd, because te 5th is actually the second in its group within its div.item:

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

So is there a way to get the index of the clicked element within the array of the selection, instead of within the parent in the DOM?

I have an HTML structure like this:

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

I select all the A-s with jQuery, and get a total of 6 objects here. I want to get the index of the A in the array of 6 (so I can detect which A has been clicked, for example), but when I use .index() I get the index of the element relative to its parent. So for the 5th A I get the same index as for the 2nd, because te 5th is actually the second in its group within its div.item:

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

So is there a way to get the index of the clicked element within the array of the selection, instead of within the parent in the DOM?

Share Improve this question asked Mar 9, 2015 at 21:58 vladko13vladko13 3041 gold badge2 silver badges7 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 7

You can pass the clicked element to the index method:

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

Take a look at jquery documentation for .index(). You could modify your code as following to get the desired result:

$('.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>

发布评论

评论列表(0)

  1. 暂无评论