javascript - 如何使用 $(this) 获取动态 DIV 中图像的 src

标签 javascript jquery html this

我试图获取图像的src,但是div是动态的,然后在页面上出现多次,当我点击DIV时,他总是获取第一帧而不是点击的DIV,怎么办我正确使用了 $(this) 吗?遵循我正在使用的代码:

<section class="clientes" role="region">
    <a href="" title="Cliente" class="group">
        <img src="img/image01.jpg" alt="" />

        <h2>The title</h2>

        <p>content here</p>
    </a>
</section>

<script>
$("body").on("click", ".clientes", function(){
    var pega = $(".clientes .dsp-none img").attr('src');
    $(this).find("a").attr("href", pega);
})

最佳答案

利用 jQuery 安排 this 来引用单击的 DOM 元素:

var pega = $(this).find(".dsp-none img").attr('src');

您可能想也可能不想使用 .prop("src") 而不是 .attr()

关于javascript - 如何使用 $(this) 获取动态 DIV 中图像的 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27809272/

相关文章:

javascript - 如何使用 react-native-fbsdk 提供的 LoginManager 从 facebook 注销?

javascript - 确认 asp.net 按钮后触发回发警报

php - php 脚本 JSON 字符串中的后台事件 FullCalendar 存在问题

html - FlexBox - 使用百分比边距时容器宽度不扩展

javascript - 在另一个函数加载后加载一个函数

php - 将 PHP 数组解析为 JavaScript 数组

javascript - 在 Javascript 中导出动态名称

javascript - 提交没有表单的输入

javascript - 在 CodeIgniter 中使用 Bootstrap 提交 jQuery 表单

php - Jquery onblur 第二次不工作