使用 jQuery 获取集合中被点击元素的索引

问题描述 投票:0回答:7

如何在下面的代码中获取点击项目的索引?

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

使用 Firebug,我看到了这个:

jQuery151017197709735298827: 2
(我点击了第二个元素)。

javascript jquery events jquery-selectors
7个回答
125
投票

这将提醒被点击的选择器的索引(第一个从 0 开始):

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

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

jsfiddle


32
投票

兄弟姐妹

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


11
投票

就这样做:-

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

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

2
投票

看看这个 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)

1
投票

如果你正在使用 .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))

0
投票
$('selector').click(function (event) {
    // get index in collection of the clicked item ...
    alert($(this).index());
});
© www.soinside.com 2019 - 2024. All rights reserved.