2010-04-29 138 views
17

我试过了几个网站的一些HTML DOM代码,但它不工作。它没有添加任何东西。有没有人有这个工作的例子?用javascript将图像添加到html

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

但它没有添加任何东西到div。 (gamediv)我也试过document.body,没有结果。

在此先感谢。

回答

36

您需要使用document.getElementById()在第3行

如果您在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); 

...你会得到这样的:

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); 现在改变了它,但它仍然不会在div gamediv中弹出。 – Anonymous 2010-04-29 08:51:01

+0

@klausbyskov:感谢您修复错字。 – 2010-04-29 08:53:14

+0

@Anonymous:难道是'src'路径不正确?你可以尝试一个绝对路径的图像,你知道肯定存在吗?如:'http:// www.google.com/intl/en_com/images/logo_plain.png' – 2010-04-29 08:54:44

1

摆脱语句太

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

为什么?这是一堂课。 – Anonymous 2010-04-29 09:01:39

3

这工作的:

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

或者使用jQuery:

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

随着一点点的研究,我发现, JavaScript不知道一个文档对象存在,除非对象已经在脚本代码之前加载(当JavaScript读取页面时)。

<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

,或者就

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