首页 新闻 会员 周边

js 节点操作出错

0
[已解决问题] 解决于 2016-10-13 15:39

js 节点操作出错

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript">
    var img1=document.createElement("img");
    img1.setAttribute("src","../img/1.jpg");
    document.body.appendChild(img1);
</script>
<body>
</body>
</html>

Uncaught TypeError: Cannot read property 'appendChild' of null

img1怎么变为null ?

js
gyz418的主页 gyz418 | 菜鸟二级 | 园豆:202
提问于:2016-02-22 15:58
< >
分享
最佳答案
0

document.body为null,因为你的script位于body之上,在执行script的时候body还处于unload的状态。可在document加载完后执行该script,可改成这样:

window.onload = function () {
        var img1 = document.createElement("img");
        img1.setAttribute("src", "1.jpg");
        document.body.appendChild(img1);
    }

 

奖励园豆:5
jello chen | 大侠五级 |园豆:7336 | 2016-02-22 16:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册