使用javascript将图像添加到HTML文档

时间:2010-04-29 08:44:14

标签: javascript html dom image

我已尝试过来自多个网站的一些HTML DOM代码,但它无效。它没有添加任何东西。有没有人有这方面的工作实例?

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,没有结果。

提前致谢。

6 个答案:

答案 0 :(得分:39)

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

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

答案 1 :(得分:4)

这有效:

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');

答案 2 :(得分: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 :(得分: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>

答案 4 :(得分:1)

摆脱语句

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

答案 5 :(得分:-1)

需要思考的事情:

  1. Use jquery
  2. 哪个this是您的代码,指的是
  3. 通常getElementById不是document.getElementById
  4. 如果找不到图片,are you sure your browser would tell you
相关问题