【问题标题】:How get the src value from the img clicked如何从点击的img中获取src值
【发布时间】:2016-05-01 17:40:49
【问题描述】:

我会得到点击的 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'));
});

但我不明白我错在哪里。 有人可以帮我吗?

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 您忘记包含 Jquery 文件 :)。检查我的回答:)

标签: jquery image get click src


【解决方案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>

【讨论】:

    【解决方案2】:

    您的页面中是否包含 Jquery。从您提供的提琴手链接中,很明显 Jquery 不包含在“未捕获的 ReferenceError:$ 未定义”错误即将到来

    【讨论】:

    • 感谢您的回答,问题是缺少行code$(document).ready(function () {
    【解决方案3】:

    您的 jsFiddle 工作正常,但您必须添加 jQuery 库,使用齿轮单击单词 javascript 并在“框架和扩展”输入中选择 jQuery。

    但是你的代码是对的。

    【讨论】:

    • 感谢您的回答,问题是缺少行code$(document).ready(function () {
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    相关资源
    最近更新 更多