获取jQuery选择器的数组索引

时间:2014-08-05 09:52:56

标签: javascript jquery arrays dom traversal

我有一组按钮,我选择使用类名:

<button class="validator">One</button>
<button class="validator">Two</button>
<button class="validator">Three</button>
<button class="validator">Four</button>
<button class="validator">Five</button>

我知道jQuery的数组中有5个按钮,因为:

$(".validator").length;
// returns 5

比如说我单击按钮“Three”,如何在数组中得到它的索引(在这个例子中是2)?

3 个答案:

答案 0 :(得分:2)

工作演示:JSFiddle

$('.validator').on('click', function() {
  alert($(this).index());
});

有关详细信息,请参阅here

答案 1 :(得分:0)

$('button').on('click', function() { console.log($(this).index()); });

答案 2 :(得分:0)

试试这个

jQuery(function(){

    jQuery('.validator').click(function(i){
            console.log(jQuery(this).index());
    });
})

JS小提琴:http://jsfiddle.net/X74Qw/