<html>
<head>
<title> OLL </title>
</head>
<body>
<script type=text/javascript>
//Loads Images
//img.src = 'path/to/image.jpg';
var img = new Image();
var div = document.getElementById('foo');
img.onload = function() {
div.appendChild(img);
};
//img.src = 'path/to/image.jpg';
img.src = 'bone.jpg';
</script>
</body>
</html>
每当我在Chrome上打开它时,它都不会显示bone.jpg
bone.jpg
与html文件位于同一文件夹中,当我打开控制台时,它会显示
无法阅读属性&quot; appendChild&#39;在Image.img.onload上的null
我是JavaScript的新手,所以请尽量简化您的回复。
答案 0 :(得分:2)
您需要在标记中添加ID为foo
的div才能附加到:
<html>
<head>
<title> OLL </title>
</head>
<body>
<div id="foo"></div>
<script type=text/javascript>
var img = new Image();
var div = document.getElementById('foo');
img.onload = function() { div.appendChild(img); };
img.src = 'bone.jpg';
</script>
</body>
</html>
答案 1 :(得分:2)
您需要在HTML标记中添加标识为<div>
的{{1}},否则您的脚本无法找到具有此类ID的元素并返回foo
,而不能附加到:
null
完整代码:
[...]
<body>
<div id="foo"></div>
<script type=text/javascript>
[...]