Get index of the element I clicked on relative to the jquery collection

ε祈祈猫儿з 提交于 2019-12-01 11:14:04
lonesomeday

You need to store the original collection and call index on that collection.

var links = $('section a').on('click', function() {
    alert(links.index(this));
});

jsFiddle


The problem with your code is that $(this).index() will get the index of the element relative to its siblings. Since the a elements don't have any siblings, the index is always 0. The API page I've linked explains how index function works if a DOM element is the argument.

lonesomeday has a good way to do it but another way is:

$('section a').on('click', function(e) {
    alert( $.inArray(e.target, $('section a')) );
});​

jsFiddle example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!