How to get the array number of the element I clicked JQUERY?

Asked

Viewed 179 times

-2

inserir a descrição da imagem aqui

How do I get the number of the vector of an img for example? See there in the image several img right? I want something where the moment I click on the image I can get the number of that img, some function,

  • https://api.jquery.com/index/

  • Never use code in image copy paste

  • It is impossible for me to do a mouse effect on the image when it gets dark by cutting the image. as it does?

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>

If you want a given action to occur on a given element based on its index (position within a vector) you can do:

$('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>

In this case the click event was only delegated to the third div.

You can also use 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.