How to get the element vector number that I clicked JQUERY? [closed]

-2

How do I get the vector number of an img for example? You see there in the image several img right? I want something in the moment that I click on the image I can get the number of this img, some function, gambiarra I do not know pff

    
asked by anonymous 04.09.2017 / 16:13

1 answer

3

You can do with index () :

$('div').on('click', function() {
  alert('O elemento encontra-se na posição ' +$(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>Hey</div><div>Hey</div><div>Hey</div><div>Hey</div><div>Hey</div>

Ifyouwantagivenactiontooccuronagivenelementbasedonitsindex(positionwithinavector)youcando:

$('div').eq(2).on('click', function() {
  alert('Clicou no elemento ' +$(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>Hey</div><div>Hey</div><div>Hey</div><div>Hey</div><div>Hey</div>

Inthiscase,theclickeventwasonlydelegatedtothethirddiv.

Youcanalsouse child css selectors

$('div:nth-child(3)').on('click', function() {
    alert('Clicou no elemento ' +$(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Hey</div>
<div>Hey</div>
<div>Hey</div>
<div>Hey</div>
<div>Hey</div>
    
04.09.2017 / 16:33