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

前端 未结 2 1884
抹茶落季
抹茶落季 2021-01-14 22:35

I have a fiddle here, very simple one.

http://jsfiddle.net/tnQne/

The js I have is here

$(\'section a\').on(\'click\', function() {
    alert         


        
2条回答
  •  花落未央
    2021-01-14 23:03

    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.

提交回复
热议问题