使用 javascript 向 div 添加 img 元素

我正在尝试使用 JavaScript 向 placehere div 添加一个 img,但是我运气不佳。有人能帮我写一下代码吗?

<html>
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>


<div id="placehere">


</div>


</body>
</html>
246289 次浏览
document.getElementById("placehere").appendChild(elem);

没有

document.getElementById("placehere").appendChild("elem");

并使用下面的设置源

elem.src = 'images/hydrangeas.jpg';

它应该是:

document.getElementById("placehere").appendChild(elem);

并将 div放在 Javascript之前,因为如果不这样做,Javascript将在 div存在之前执行。或者等它上膛。你的代码是这样的:

window.onload = function() {
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
<div id="placehere"></div>

To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.

function image()
{
//dynamically add an image and set its attribute
var img=document.createElement("img");
img.src="p1.jpg"
img.id="picture"
var foo = document.getElementById("fooBar");
foo.appendChild(img);
}


<span id="fooBar">&nbsp;</span>

The following solution seems to be a much shorter version for that:

<div id="imageDiv"></div>

在 Javascript 中:

document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';

如果有人想知道如何使用 JQuery:

$("<img height='200' width='200' alt='testImage' src='https://avatars.githubusercontent.com/u/47340995?v=4'> </img>").appendTo("#container");

档号: https://api.jquery.com/jQuery/#jQuery2