I wrote this code:

<div class="details"> <img src="" id="foto1"> <img src="" id="foto2"> <img src="" id="foto3"> <img src="" id="foto4"> </div> $('.details').on('click', function(){alert($(this).index())}) 

How to do it so that when you click on the first photo (id = "foto1") index 0 comes out, on the second photo (id = "foto2") index 1, etc. ?

    1 answer 1

    You need to add a click handler to the image itself. For this you can use for example delegation:

     $('.details').on('click','img', function(){alert($(this).index())}) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="details"> <img src="#" id="foto1"> <img src="#" id="foto2"> <img src="#" id="foto3"> <img src="#" id="foto4"> </div>