最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Changing 'innerHTML' on <img> not changing image - Stack Overflow

programmeradmin5浏览0评论

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 bee shown when the button is clicked. However, it's not happening. Why?

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 bee shown when the button is clicked. However, it's not happening. Why?

Share Improve this question edited Jul 26, 2012 at 14:20 merv 76.9k17 gold badges214 silver badges277 bronze badges asked Jan 17, 2012 at 17:41 sovonsovon 9072 gold badges13 silver badges30 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 9

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);
}
发布评论

评论列表(0)

  1. 暂无评论