更改'innerHTML'在<img>不改变图像

Changing 'innerHTML' on <img> not changing image

本文关键字:改变 图像 gt innerHTML 更改 lt img      更新时间:2023-09-26

这是我的代码:

HTML

<form>
  <img id='image' src=""/>
  <input type='text' id='text'>
  <input type="button" value="change picture" onclick="changeimage()">
</form>

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
}

我有一些GIF图片。我想在文本框中写一个图像名称,然后在单击按钮时显示图像。然而,这并没有发生。为什么?

您应该这样做:

document.getElementById('image').src = c;

通过执行document.getElementById('image').innerHTML=b,您试图在<img>标记中定义HTML,这是不可能的。

完整脚本:

function changeimage() {
    var a = document.getElementById('text').value;
    var c = a + ".gif";
    document.getElementById('image').src = c;
}

试试这个:

<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")

为了更新<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);
}