使用javascript将图像添加到HTML文档
问题描述:
我已经从多个站点尝试了一些HTML DOM代码,但是它不起作用。它没有添加任何东西。有人在这方面有可行的例子吗?
I've tried some HTML DOM code from several sites, but it isn't working. It isn't adding anything. Does anyone have a working example on this?
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,但没有结果。
But it isn't adding anything to the div. (gamediv) I've tried document.body as well, with no result.
预先感谢。
答
您需要使用 document.getElementById()。
如果您现在在控制台中尝试以下操作:
If you try this right now in the console:
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);
<div id="header"></div>
...你会得到这个:
... you'd get this: