Javascript 使用 jQuery 更改图像 src onClick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13894815/
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
Changing image src onClick with jQuery
提问by michaelmcgurk
I am using this HTML on my site:
<a href="#1" id="slick-toggle"><img src="img1.jpg"/></a>
我在我的网站上使用这个 HTML:
<a href="#1" id="slick-toggle"><img src="img1.jpg"/></a>
When I click this link, I would like to change the image src to img2.jpg. And revert back to img1.jpgwhen clicked again & so on. Can someone explain how I do this using jQuery?
当我单击此链接时,我想将图像 src 更改为img2.jpg. 并img1.jpg在再次单击时恢复到等等。有人可以解释我如何使用 jQuery 做到这一点吗?
Here is my existing jQueryif this helps:
如果有帮助,这是我现有的jQuery:
$(document).ready(function() {
$('#slick-toggle').click(function() {
$('#slickbox').toggle(400);
return false;
});
});
Many thanks for any pointers with this :-)
非常感谢您对此的任何指示:-)
回答by thecodeparadox
$(document).ready(function() {
$('#slick-toggle').click(function() {
$('img', this).attr('src', function(i, oldSrc) {
return oldSrc == 'img1.jpg' ? 'img2.jpg' : 'img1.jpg';
});
$('#slickbox').toggle(400);
return false;
});
});
回答by Chipmunk
You need to find the image inside since your click handler is on the that wraps it, like this:
您需要在里面找到图像,因为您的点击处理程序在包装它的 上,如下所示:
$('a#slick-toggle').click(function() {
var img = $('#share')[0], isSwap = "True";
img.src = isSwap ? img.src.replace("_img1","_img2") : img.src.replace("_img2","_img1");
$('.img-swap').toggleClass("on");
$('#atBox').toggle(100);
return false;
});
回答by Ashish Panwar
Use this function for this:
为此使用此功能:
$('#mylink').toggle(
function(){
$(this).attr('src','img2.jpg');
},
function(){
$(this).attr('src','img3.jpg');
}
// and so on..
);
you can add more function in it...
您可以在其中添加更多功能...

