簡體   English   中英

jQuery:如何獲取選擇數組中元素的索引?

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

我有這樣的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>

我選擇所有的As與jQuery,並在這里獲得總共6個對象。 我想得到6的數組中的A的索引(例如,我可以檢測到哪個A被點擊),但是當我使用.index()時,我得到元素相對於其父元素的索引。 因此,對於第5個AI獲得與第2個相同的索引,因為te 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM