how to swap Image in jquery

浪子不回头ぞ 提交于 2019-12-11 02:59:56

问题


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")
});

回答1:


You can try this solution:

$("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");
})

See my demo - JSFiddle




回答2:


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');
});


来源:https://stackoverflow.com/questions/8277524/how-to-swap-image-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!