gpt4 book ai didi

javascript - 类型错误 : button is null but working fine in console

转载 作者:太空宇宙 更新时间:2023-11-04 14:26:35 24 4
gpt4 key购买 nike

所以我想制作一个网页,点击按钮时,背景颜色会发生变化。

它在浏览器中加载时显示 TypeError,但在控制台上粘贴相同的 JavaScript 后它工作正常。


代码片段

var colors = ["#0af5fa", "#0ab1fa", "#0a3efa", "#560afa", "#b70afa", "#fa0ad9", "#fa0a65", "#fa0a1e", "#fa5e0a", "#facc0a", "#cbfa0a", "#69fa0a", "#0afa1b", "#0afa77", "#0afae5", "#0a8efa"];

var flag = 0,
blinkCount = 0;

function blink() {
if (blinkCount == 15) {
blinkCount = 0;
blink();
} else {
var h1 = document.querySelector("h1");
var body = document.querySelector("body");

h1.style.color = colors[blinkCount];
body.style.background = colors[blinkCount];
blinkCount++;
}
}

var button = document.querySelector("button");
button.addEventListener("click", blink);
button {
width: 50%;
height: 100px;
background: black;
margin-top: 300px;
margin-left: 300px;
}

h1 {
color: #0af5fa;
}

body {
background: #0af5fa;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="../JavaScript/ex153.js"></script>
<link href="../css/ex153.css" rel="stylesheet">

<head>
<meta charset="utf-8">
<title></title>
</head>

<body>
<div class="">
<button><h1>Click Me</h1></button>
</div>
</body>

</html>


在浏览器中[错误]

TypeError: button is null[Learn More]     ex153.js:25:1

最佳答案

您在文档被完全解析之前运行脚本 - 查看 <script> 高于 <body>及其 <button>

要么给脚本标签defer属性:

<script defer src="..

或者把它移到正文的底部:

    </div>
<script src="../JavaScript/ex153.js"></script>
</body>
</html>

或者将整个脚本包装在 DOMContentLoaded 监听器中:

document.addEventListener('DOMContentLoaded', function() {
var colors;
// other code
});

关于javascript - 类型错误 : button is null but working fine in console,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198707/

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