TypeError:document.body为null

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事件之间的区别