How get the src value from the img clicked
10,733
Solution 1
<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>
Solution 2
Your jsFiddle works fine, but you have to add the jQuery library, clicking on the word javascript with the gear and selecting jQuery in the "Frameworks & extensions" input.
But your code is right.
Related videos on Youtube
Author by
Davide
Updated on June 26, 2022Comments
-
Davide almost 2 years
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?
-
Davide over 8 yearsthanks for the answer, the problem was the missing line
code
$(document).ready(function () { -
Davide over 8 yearsthanks for the answer, the problem was the missing line
code
$(document).ready(function () {