gpt4 book ai didi

javascript - TypeError: document.body 为空

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:32 26 4
gpt4 key购买 nike

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

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 的事件监听器中。

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

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


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

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

参见:Difference between DOMContentLoaded and Load events

关于javascript - TypeError: document.body 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27833117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com