因此,我想制作一个网页,单击该按钮,背景颜色就会改变。
它在浏览器中加载时显示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>
上方如何?
给script标签加上defer
属性:
<script defer src="..
或将其移至主体底部:
</div>
<script src="../JavaScript/ex153.js"></script>
</body>
</html>
或将整个脚本包装在DOMContentLoaded侦听器中:
document.addEventListener('DOMContentLoaded', function() {
var colors;
// other code
});
关于javascript - TypeError:按钮为空,但在控制台中工作正常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50198707/