如何从img中获取src值

时间:2016-01-25 12:04:12

标签: jquery image get click src

我会得到一个点击img的src值。我有这个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'));
});

但我不明白我错在哪里。 有人能帮助我吗?

3 个答案:

答案 0 :(得分:2)

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>

    $(document).ready(function () {
        $('#sinistra img').click(function () {
            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>

答案 1 :(得分:1)

你的jsFiddle运行正常,但你必须添加jQuery库,点击带有齿轮的单词javascript并在“Frameworks&amp; extensions”输入中选择jQuery。

但你的代码是对的。

答案 2 :(得分:0)

Jquery是否包含在您的页面中。从您提供的fiddler链接中可以清楚地看出,Jquery未被包含为'未捕获的ReferenceError:$未定义'错误即将来临