简体   繁体   中英

Changing 'innerHTML' on <img> not changing image

Here is my code:

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
}

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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