点击时,jQuery将一个图像的src复制到另一个图像

时间:2012-09-14 06:01:21

标签: jquery html

我该怎么做才能实现这一目标。我希望如果单击imgThumb1图像,此图像的src将复制到mainIMG,但是当我单击它时图像不会改变...我该怎么办?

$(document).ready(function(){
    $('.propertyResultImageThumb img[alt="imgThumb1"]').click(function(){
        var trial = $('img[alt="imgThumb1"]').attr('src');
        $("#mainIMG").attr("src", trial);
    });
});


<img alt="mainIMG" src="" id="mainIMG"/>
<img alt="imgThumb1" src="http://..../uploads/2012/09/Villa-Located-In-Almansa.jpg" />

4 个答案:

答案 0 :(得分:5)

$(document).ready(function(){
    $('img[alt="imgThumb1"]').click(function(){
        var trial = $('img[alt="imgThumb1"]').attr('src');
        $('img[alt="mainIMG"]').attr("src", trial);
    });
});

DEMO


我的代码

$(function(){
    $('#first').click(function(){
        $("#second").attr("src", $(this).attr('src'));
    });
});

<img src="" id="first"/>
<img src="" id="second" />

答案 1 :(得分:1)

尝试将html包装在一个容器中,该容器将具有class propertyResultImageThumb

<div class="propertyResultImageThumb ">
<img alt="mainIMG" src="" id="mainIMG"/>
<img alt="imgThumb1" src="http://..../uploads/2012/09/Villa-Located-In-Almansa.jpg" />
</div>     

然后就这样做

$(document).ready(function(){
    $('.propertyResultImageThumb img[alt="imgThumb1"]').click(function(){
        var trial = $(this).attr('src');
        $("#mainIMG").attr("src", trial);
    });
});

答案 2 :(得分:0)

你需要一个类名为“propertyResultImageThumb”的父dom元素  检查jsfiddle

http://jsfiddle.net/erwKP/1/

答案 3 :(得分:0)

如果你想复制没有它的图像再次从服务器下载(如果是验证码,它可能会改变),那么应该使用这个代码:

$(function(){
    $('#first').click(function(){
        img_copy(document.getElementById('#first'),document.getElementById('#second'));
    });
});

//copy src to destination without destination to download the image
function img_copy(src,destination)
{
     var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.drawImage(src, src.width, src.height);
    var dataURL = canvas.toDataURL();
    destination.src = dataURL;
}



<img src="" id="first"/>
<img src="" id="second" />