如何在 HTML 中动态更改图像的来源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1942040/
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 change the source of an image dynamically in HTML?
提问by Josh
Please help me with this question I am trying to change the source of an image dynamically.
请帮我解决这个问题我正在尝试动态更改图像的来源。
回答by Sampson
Client-side (Dynamic) Image-Swapping...
客户端(动态)图像交换...
You'll need to use javascript for this:
为此,您需要使用 javascript:
<img src="image1.jpg" id="myImage" />
<img src="image1.jpg" id="myImage" />
<script type="text/javascript">
document.getElementById("myImage").src = "image2.jpg";
</script>
Introducing jQuery...
引入jQuery...
If this is the type of response you are looking for, then I would also like to extend an invitation to you to start checking out and javascript framework like jQuery, which makes this type of stuff much easier to do/manage. In jQuery, you can accomplish the same thing with the following code:
如果这是您正在寻找的响应类型,那么我还想邀请您开始检查和jQuery 之类的javascript 框架,这使此类内容更易于执行/管理。在 jQuery 中,您可以使用以下代码完成相同的操作:
$("#myImage").attr("src", "image2.jpg");