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

IT技术 javascript jquery events jquery-selectors
2021-01-21 15:16:20

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

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

使用 Firebug 我看到了这个:(jQuery151017197709735298827: 2我点击了第二个元素)。

6个回答

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

$('selector').click(function(){
    alert( $('selector').index(this) );
});
2021-03-14 15:16:20
伟大的!谢谢!获得正确索引的最佳解决方案取决于父元素。
2021-03-27 15:16:20
是的,如果我们没有对“this”的引用,但只知道添加的类的元素,我们可以使用这种方法
2021-03-29 15:16:20
首先我认为selector是多余的,但是如果在同一个父级中有其他元素(可通过其他选择器访问),这就对了
2021-04-01 15:16:20
$('selector').click(function (event) {
    alert($(this).index());
});

提琴手

这给我带来了一些问题。返回的索引不正确。不过@Ant 的解决方案对我有用。
2021-03-23 15:16:20
抱歉,这个答案(经常)是错误的。它返回其直接父级中被点击元素的索引,因此如果选择了一些按钮,并且每个按钮都包含在自己的 div 中,那么索引将始终为 0
2021-03-25 15:16:20

兄弟姐妹

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


不是兄弟姐妹

如果没有参数传递给该.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>

小提琴

啊,“不是兄弟姐妹”就是我要找的人!
2021-04-01 15:16:20

就这样做: -

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