简体   繁体   中英

How to create an IMG when I click on a button?

Now I have this:

<script>
 function load() { 
 var el = document.getElementById('load');
 el.innerHTML='<img src=\"load.png\">'; }
</script>

And the html:

<input type="submit" onclick="javascript:load();"> 
<span id="load"> </span>

but that doesn't work, because i may not put < and > within the el.innerHTML='' . Does anyone know an alternative?

TIA

The whole point of innerHTML is that you can use < and > inside it. You have some pointless escaping of quotes, and the cargo-cult javascript: label , but the script works.

It probably just looks like it is failing because the form submits and the browser leaves the page before the image loads.

Use jQuery!

<button id="button">Click</button>

$(document).ready(function(){
    $("#button").click(function(){
        $("#load").append("<img src='\load.png\'/>");
    });
});

You should create the element using createElement() method and then append it to your container:

var el = document.getElementById('load');
var img = document.createElement('img');
img.src = 'test.png';
el.appendChild(img);
alert(el.innerHTML);

See this DEMO .

You might try this:

javascript:

 function showImage(){
     document.getElementById('load').style.display = 'block';
  }

html:

 <input type="submit" onclick="showImage();">
 <span id="load" style="display:none;"><img src="load.png"></span>

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