how to swap Image in jquery

2019-07-18 00:26发布

How can I swap an image's SRC attribute, on click of that image?

<a href="#">
    <img src="./layout/images/search.png" />
</a>

$('img[src="./layout/images/search.png"]').click(function () {
    $(this).attr('src',"./layout/images/search_select.png")
});

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-18 00:56

If you have an image with a class called 'swap', you can use the following snippet. It uses the click event, and then attr, to change the images src attribute.

$('.swap').click(function(){ 
    $(this).attr('src','new/path/to/img.jpg');
});
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-18 01:14

Try this -

$("img").click(function () {
   $(this).attr("src","new.gif")
})

As David Hedlund points out this will change all images on a page due to the img selector. You could target an image using a class as sam152 suggests or, you could target an image using it's src attribute -

 $("img[src='old.gif']").click(function () {
   $(this).attr("src","new.gif")
})

Demo - http://jsfiddle.net/W7mq6/

查看更多
登录 后发表回答