javascript 类型错误:document.body 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27833117/
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
TypeError: document.body is null
提问by Getup4
Why I getting error in browser?
为什么我在浏览器中出错?
TypeError: document.body is null
类型错误:document.body 为空
Code is working well in JSfiddle.
代码在JSfiddle 中运行良好。
HTML
HTML
<head>
<meta charset="UTF-8">
<title></title>
<script src="jsscript.js"></script>
</head>
<body>
</body>
JS
JS
var creElem = document.createElement("p");
creElem.innerHTML = "Hellow World";
creElem.setAttribute("id", "id_name");
document.body.appendChild(creElem);
回答by Josh Crozier
Execute the code when the DOM loads. Wrap your logic in an event listener for DOMContentLoaded
.
在 DOM 加载时执行代码。将您的逻辑包装在事件侦听器中DOMContentLoaded
。
document.addEventListener('DOMContentLoaded', function () {
// ...
});
The reason it worked in JSFiddle is because the JS is executed on load (that's the default option in JSFiddle).
它在 JSFiddle 中工作的原因是因为 JS 在加载时执行(这是 JSFiddle 中的默认选项)。
Alternatively, depending on when you need the logic to be executed, you could also use:
或者,根据您何时需要执行逻辑,您还可以使用:
window.addEventListener('load', function () {
// ...
});
回答by Sharifullah Sharif
Your document.body
is not crated or existed yet. If you want to append child to document.body
or do anything with document.body
in your javascript then put your javascript cod or link of js file in the end of body tag.
你的document.body
还没有装箱或存在。如果你想在你的 javascript 中附加孩子document.body
或做任何事情,document.body
那么把你的 javascript cod 或 js 文件的链接放在 body 标签的末尾。
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="jsscript.js"></script>
</body>
</html>