如何检索用户单击的图像的图像源?(jQuery)

How do you retrieve the image source of an image that the user has clicked on? (jQuery)

本文关键字:图像 jQuery 用户 何检索 检索 单击      更新时间:2023-09-26

我正在尝试检索用户单击的图像的图像源。这就是我所拥有的,它似乎不起作用:

var imgSrc = getSrc(image)
    function getSrc(image) {
        $('img').each(function() {
            $(this).click(function() {
                $(this).attr('src')
            }); //end click
        }); //end each  
    } //end getSrc
$('img').click(function() {
    alert( $(this).attr('src') ); // or this.src
 }); 

你不需要任何循环。我认为上面的代码可以正常工作。

完整代码

function getSrc(image) {
   var src;
   $('img').click(function() {
     src = $(this).attr('src'); // or this.src
   }); 
   return src;
}

注意

在您的问题中,您不会在代码中使用image参数。我不确定你为什么要使用它。如果你想使用获取你通过参数传递的image src,那么你可以尝试:

$(image).attr('src');

您不会从函数返回任何内容。 此外,您不需要 .each() 调用,因为您知道已单击的图像:

var imgSrc = '';
$(document).ready(function () {
    $('img').click(function () {
        imgSrc = $(this).attr('src');
    });
});