2010-04-29 16 views
17

He intentado con algunos códigos HTML DOM desde varios sitios, pero no está funcionando. No está agregando nada. ¿Alguien tiene un ejemplo de trabajo en esto?Agregar imágenes al html con javascript

this.img = document.createElement("img"); 
this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; 
src = getElementById("gamediv"); 
src.appendChild(this.img) 

Pero no agrega nada al div. (gamediv) He intentado document.body también, sin ningún resultado.

Gracias de antemano.

Respuesta

36

Es necesario utilizar document.getElementById() en la línea 3.

Si intenta esto en este momento en la consola de Firebug:

var img = document.createElement("img"); 
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png"; 

var src = document.getElementById("header"); 
src.appendChild(img); 

... se obtendría esto:

Adding images to the HTML with JavaScript http://img94.imageshack.us/img94/3769/googso2.png

+0

this.img = document.createElement ("img"); this.img.src = "img/eqp /" + this.apparel + "/" + this.facing + "_ idle.png"; src = document.getElementById ("gamediv"); src.appendChild (this.img); Se ha cambiado ahora, pero todavía no aparece en el div gamediv. – Anonymous

+0

@klausbyskov: Gracias por corregir el error tipográfico. –

+0

@Anonymous: ¿Podría ser que la ruta 'src' es incorrecta? ¿Puedes probar una imagen con una ruta absoluta, que sabes que existe? Tales como: 'http: //www.google.com/intl/en_com/images/logo_plain.png' –

1

deshacerse de los esta declaraciones demasiado

var img = document.createElement("img"); 
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; 
src = document.getElementById("gamediv"); 
src.appendChild(this.img) 
+0

¿Por qué? Está en una clase. – Anonymous

3

esto funciona:

var img = document.createElement('img'); 
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png'; 
document.getElementById('gamediv').appendChild(img) 

O usando jQuery:

$('<img/>') 
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png') 
.appendTo('#gamediv'); 
4

Con un poco de investigación he encontrado que javascript no sabe que una Objeto de documento Existe a menos que el Objeto ya se haya cargado antes del código del script (Como javascript lee una página).

<head> 
    <script type="text/javascript"> 
     function insert(){ 
      var src = document.getElementById("gamediv"); 
      var img = document.createElement("img"); 
      img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; 
      src.appendChild(img); 
     } 
    </script> 
</head> 
<body> 
    <div id="gamediv"> 
     <script type="text/javascript"> 
      insert(); 
     </script> 
    </div> 
</body> 
3

o simplemente puede

<script> 
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the the script)*\"') 
document.getElementById('pic') 
</script> 
<div id="pic"> 
</div> 
Cuestiones relacionadas