Get Index Of The Element I Clicked On Relative To The Jquery Collection
I have a fiddle here, very simple one. http://jsfiddle.net/tnQne/ The js I have is here $('section a').on('click', function() { alert($(this).index()); }); It always returns 0
Solution 1:
You need to store the original collection and call index
on that collection.
var links = $('section a').on('click', function() {
alert(links.index(this));
});
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.
Solution 2:
lonesomeday has a good way to do it but another way is:
$('section a').on('click', function(e) {
alert( $.inArray(e.target, $('section a')) );
});
Post a Comment for "Get Index Of The Element I Clicked On Relative To The Jquery Collection"