jQuery 如何在jquery中交换图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8277524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to swap Image in jquery
提问by user1065056
How can I swap an image's SRC attribute, on click of that image?
如何在单击该图像时交换图像的 SRC 属性?
<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")
});
回答by ipr101
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 -
正如 David Hedlund 指出的那样,由于img
选择器,这将更改页面上的所有图像。您可以使用 sam152 建议的类来定位图像,或者,您可以使用它的src
属性来定位图像-
$("img[src='old.gif']").click(function (){
$(this).attr("src","new.gif");
})
See my demo - JSFiddle
看我的演示 - JSFiddle
回答by Sam152
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 事件,然后使用 attr 来更改图像的 src 属性。
$('.swap').click(function(){
$(this).attr('src','new/path/to/img.jpg');
});