Search code examples
jqueryimagegetclicksrc

How get the src value from the img clicked


I would get the src value of an img clicked. I have this HTML https://jsfiddle.net/4k541boj/code

 <span id="sinistra">
        <img src="http://www.bicielettriche.bikeitalia.it/wp-content/uploads/2014/11/bici-elettrica-piaggio.png">
        <img src="https://eradellabicicletta.files.wordpress.com/2013/01/bici-da-corsa-rb1000-team-edition.jpg">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9ty91M-QHPrgy6woAJAgdF68UrTD8c91WXz5dfznU1R_2GQ5Qjw">
        </span>

$('#sinistra img').click(function(){
   alert($(this).attr('src'));
});

But i don't understand where i'm wrong. can someone help me?


Solution

  • <html>
      <head>
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script>
          $(document).ready(function () {
            // Listen for clicks to "img" elements inside the element where id="sinistra"
            $("#sinistra img").click(function () {
              // Displays the source of the image clicked
              alert($(this).attr("src"));
            });
          });
        </script>
      </head>
      <body>
        <span id="sinistra">
          <img
            src="http://www.bicielettriche.bikeitalia.it/wp-content/uploads/2014/11/bici-elettrica-piaggio.png"
          />
          <img
            src="https://eradellabicicletta.files.wordpress.com/2013/01/bici-da-corsa-rb1000-team-edition.jpg"
          />
          <img
            src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9ty91M-QHPrgy6woAJAgdF68UrTD8c91WXz5dfznU1R_2GQ5Qjw"
          />
        </span>
      </body>
    </html>