有一个未被发现的打字错误,不知道为什么

Getting an uncaught typerror and don't know why

本文关键字:错误 不知道 为什么 被发现 有一个      更新时间:2023-09-26

我正在为一点javascript而挣扎。

我有这四行:

var footer = document.getElementById('footer');
var cookieBanner = document.createElement('div');
cookiebanner.className = "cookieBanner";
footer.appendChild(cookiebanner);

但是在控制台我得到

Uncaught TypeError: Cannot read property 'appendChild' of undefined

如果我在控制台中做同样的事情,它会工作。为什么会这样?

var footer = document.getElementById('footer');返回undefined。因此,当您尝试在undefined上调用appendChild时,您将得到:

Uncaught TypeError: Cannot read property 'appendChild' of undefined

如果您的页面上有一个具有该ID的元素,请确保在运行此脚本之前呈现您的页面。

相关文章: