简体   繁体   English

改变&#39;innerHTML&#39; <img> 不改变形象

[英]Changing 'innerHTML' on <img> not changing image

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. 我有一些GIF图像。 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? 为什么?

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

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>
document.getElementById("image").setAttribute("src","another.gif")

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM