javascript 更改 <img> 上的“innerHTML”而不更改图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8899166/
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 'innerHTML' on <img> not changing image
提问by sovon
Here is my code:
这是我的代码:
HTML
HTML
<form>
<img id='image' src=""/>
<input type='text' id='text'>
<input type="button" value="change picture" onclick="changeimage()">
</form>
JavaScript
JavaScript
function changeimage() {
var a=document.getElementById('text').value
var c=a+".gif"
c="\""+c+"\""
var b= "<img src="+c+"\/>"
document.getElementById('image').innerHTML=b
}
I have some GIF images. I want to write an image name in the textbox and then have the image become shown when the button is clicked. However, it's not happening. Why?
我有一些 GIF 图片。我想在文本框中写一个图像名称,然后在单击按钮时显示图像。然而,这并没有发生。为什么?
回答by Didier Ghys
You should do this:
你应该做这个:
document.getElementById('image').src = c;
By doing document.getElementById('image').innerHTML=b
you are trying to defined the HTML inside the <img>
tag which is not possible.
通过这样做,document.getElementById('image').innerHTML=b
您试图在<img>
标签内定义 HTML,这是不可能的。
Full script:
完整脚本:
function changeimage() {
var a = document.getElementById('text').value;
var c = a + ".gif";
document.getElementById('image').src = c;
}
回答by Michael Irwin
Try this instead:
试试这个:
<html>
<body>
<script type="text/javascript">
function changeimage() {
var a = document.getElementById('text').value;
document.getElementById('image').src = a + '.gif';
}
</script>
<form>
<img id='image' src=""/>
<input type='text' id='text'>
<input type="button" value="change picture" onclick="changeimage()">
</form>
</body>
</html>
回答by Alex Dn
document.getElementById("image").setAttribute("src","another.gif")
回答by JaredPar
In order to update the <img>
tag you need to update it's source, not it's inner HTML.
为了更新<img>
标签,您需要更新它的源代码,而不是它的内部 HTML。
function changeimage()
{
var a=document.getElementById('text').value
var c=a+".gif"
c="\""+c+"\""
var elem = document.getElementById('image');
elem.setAttribute('src', c);
}