Adding images to an HTML document with JavaScript
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");
thi开发者_如何学Gos.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = getElementById("gamediv");
src.appendChild(this.img)
But it isn't adding anything to the div gamediv
. I've tried document.body
as well, with no result.
You need to use document.getElementById()
in line 3.
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:
With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As JavaScript reads down a page).
<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>
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>
Use Image() instead
Instead of using document.createElement()
use new Image()
const myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').
Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)
Things to ponder:
- Use jquery
- Which
this
is your code refering to - Isnt
getElementById
usuallydocument.getElementById
? - If the image is not found, are you sure your browser would tell you?
精彩评论