簡體   English   中英

使用 jQuery 獲取集合中單擊元素的索引

[英]Get index of clicked element in collection with jQuery

如何在下面的代碼中獲取點擊項目的索引?

$('selector').click(function (event) {
    // get index in collection of the clicked item ...
});

使用 Firebug 我看到了這個: jQuery151017197709735298827: 2 (我點擊了第二個元素)。

這將提醒點擊選擇器的索引(第一個從 0 開始):

$('selector').click(function(){
    alert( $('selector').index(this) );
});
$('selector').click(function (event) {
    alert($(this).index());
});

提琴手

兄弟姐妹

如果元素是兄弟元素,則$(this).index()可用於獲取被點擊元素的索引。

<div id="container">
    <a href="#" class="link">1</a>
    <a href="#" class="link">2</a>
    <a href="#" class="link">3</a>
    <a href="#" class="link">4</a>
</div>

 $('#container').on('click', 'a', function() { console.log($(this).index()); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="container"> <a href="#" class="link">1</a> <a href="#" class="link">2</a> <a href="#" class="link">3</a> <a href="#" class="link">4</a> </div>


不是兄弟姐妹

如果沒有參數傳遞給.index()方法,則返回值是一個整數,指示 jQuery 對象中第一個元素相對於其兄弟元素的位置

將選擇器傳遞給index(selector)

$(this).index(selector);

例子:

找到被點擊的<a>元素的索引。

<tr>
    <td><a href="#" class="adwa">0001</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0002</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0003</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0004</a></td>
</tr>

小提琴

 $('#table').on('click', '.adwa', function() { console.log($(this).index(".adwa")); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <table id="table"> <thead> <tr> <th>vendor id</th> </tr> </thead> <tbody> <tr> <td><a href="#" class="adwa">0001</a></td> </tr> <tr> <td><a href="#" class="adwa">0002</a></td> </tr> <tr> <td><a href="#" class="adwa">0003</a></td> </tr> <tr> <td><a href="#" class="adwa">0004</a></td> </tr> </tbody> </table>

就這樣做: -

$('ul li').on('click', function(e) {
    alert($(this).index()); 
});

或者

$('ul li').click(function() {
    alert($(this).index());
});

看看這個https://forum.jquery.com/topic/get-index-of-same-class-element-on-click然后http://jsfiddle.net/me2loveit2/d6rFM/2/

var index = $('selector').index(this);
console.log(index)

如果你使用 .bind(this),試試這個:

let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

$(this.pagination).find("a").on('click', function(evt) {
        let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

        this.goTo(index);
    }.bind(this))

暫無
暫無

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

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