gpt4 book ai didi

javascript - 无法将属性设置为 null

转载 作者:行者123 更新时间:2023-11-30 09:16:36 24 4
gpt4 key购买 nike

我有一个 HTML、CSS 和 JS 文件。除了我的控制台之外,一切都运行良好,向我显示一条消息“无法将属性‘textContent’设置为 null”。

我已经尝试用 window.onload 围绕代码,但仍然没有成功。 html code here

Error message

游戏.js

var colors = [
'rgb(255, 0, 0)',
'rgb(255, 255, 0)',
'rgb(0, 255, 0)',
'rgb(0, 255, 255)',
'rgb(0, 0, 255)',
'rgb(255, 0, 255)'
];

var squares = document.querySelectorAll('.square');
var pickedColor = colors[3];
var display = document.getElementById('colorDisplay');
display.textContent = pickedColor;

for (var i = 0; i < squares.length; i++) {
// ADD INITIAL COLORS TO SQUARES
squares[i].style.backgroundColor = colors[i];

// ADD EVENTLISTENERS TO SQUARES
squares[i].addEventListener('click', function() {
console.log(this.style.backgroundColor);
});
}

HTML:

<!DOCTYPE html>
<html>
<head>
<title>Agent Color</title>
<link rel="stylesheet" type="text/css" href="game.css">
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<h1>The great <span id="colorDisplay">RGB</span> color game</h1>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

</body>
<script type="text/javascript" src="game.js"></script>

</html>

最佳答案

var display=document.getElementById("colorDisplay") - 这是 null 因为(至少在执行时)不存在 ID 为 颜色显示

如果您确定代码中有这样的元素,请确保您的 DOM 内容已加载。

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

关于javascript - 无法将属性设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54711588/

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