TypeError:document.body为null [英] TypeError: document.body is null

查看:307
本文介绍了TypeError:document.body为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我在浏览器中出错?

Why I getting error in browser?


TypeError:document.body is null

TypeError: document.body is null

代码在 JSfiddle 中运作良好。

HTML

<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jsscript.js"></script>
</head>
<body>
</body>

JS

var creElem = document.createElement("p");
creElem.innerHTML = "Hellow World";
creElem.setAttribute("id", "id_name");
document.body.appendChild(creElem);


推荐答案

在DOM加载时执行代码。将您的逻辑包装在 DOMContentLoaded 的事件监听器中。

Execute the code when the DOM loads. Wrap your logic in an event listener for DOMContentLoaded.

document.addEventListener('DOMContentLoaded', function () {
    // ...
});

它在JSFiddle中工作的原因是因为JS是在加载时执行的(这是JSFiddle中的默认选项) )。

The reason it worked in JSFiddle is because the JS is executed on load (that's the default option in JSFiddle).

或者,根据您需要执行逻辑的时间,您也可以使用:

Alternatively, depending on when you need the logic to be executed, you could also use:

window.addEventListener('load', function () {
    // ...
});

请参阅: DOMContentLoaded和Load事件之间的区别

这篇关于TypeError:document.body为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆