无法使用 jQuery 获取图像的 src

我有一个关闭按钮,用于获取src位于其上方的图像:


<div class="col">

    <img class="img-thumbnail" src="/path/to/image2.gif">

    <br>

    <span class="img-remove">x</span>

</div>

jQuery:


$(document).on('click', '.img-remove', function () {

    let _self = this;

    let img_src = $(this).closest('.img-thumbnail').attr("src");

    console.log('img_src', img_src);

});

src然而,我在控制台中得到的不是值:


img_src 未定义


这里出了什么问题,我该如何修复它?


30秒到达战场
浏览 95回答 2
2回答

拉莫斯之舞

更改$(this).closest('.img-thumbnail')为$(this).siblings('.img-thumbnail')将解决您的问题示例代码:$(document).on('click', '.img-remove', function () {&nbsp; &nbsp; let _self = this;&nbsp; &nbsp; let img_src = $(this).siblings('.img-thumbnail').attr("src");&nbsp; &nbsp; console.log('img_src', img_src);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="col">&nbsp; &nbsp; <img class="img-thumbnail" src="/path/to/image2.gif">&nbsp; &nbsp; <br>&nbsp; &nbsp; <span class="img-remove">x</span></div>解释:$(this)是span.img-remove,.closet()将遍历它的祖先。但你需要找到img.img-thumbnail,它是$(this)不是祖先的兄弟姐妹。所以你需要使用.siblings()来查找兄弟姐妹。

Qyouu

$(document).on('click', '.img-remove', function() {&nbsp; let _self = this;&nbsp; let img_src = $(this).closest('.col').find('.img-thumbnail').attr("src");&nbsp; console.log('img_src', img_src);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript