Javascript 使用javascript将img元素添加到div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7802744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding an img element to a div with javascript
提问by Andrew De Forest
I am trying to add an img to the placehere
div using JavaScript, however I am having no luck. Can anyone give me a hand with my code?
我正在尝试placehere
使用 JavaScript向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>
回答by Ghyath Serhal
document.getElementById("placehere").appendChild(elem);
not
不是
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
并使用以下设置源
elem.src = 'images/hydrangeas.jpg';
回答by Some Guy
It should be:
它应该是:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
并将你的 div 放在你的 javascript 之前,因为如果你不这样做,javascript 会在 div 存在之前执行。或者等待它加载。所以你的代码看起来像这样:
<html>
<body>
<script type="text/javascript">
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);
}
</script>
<div id="placehere">
</div>
</body>
</html>
To prove my point, see this with the onloadand 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.
为了证明我的观点,请查看带有 onload 的内容和不带有onload 的内容。启动控制台,您会发现一个错误,指出 div 不存在或找不到 null 的 appendChild 方法。
回答by hema
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"> </span>
回答by J W
The following solution seems to be a much shorter version for that:
以下解决方案似乎是一个更短的版本:
<div id="imageDiv"></div>
In Javascript:
在 JavaScript 中:
document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';