TypeError:button为null但在控制台中工作正常

时间:2018-05-06 10:33:05

标签: javascript html css

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

它在浏览器中加载时显示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>
&#13;
&#13;
&#13;

在浏览器中[错误]

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

1 个答案:

答案 0 :(得分:6)

您是在完全解析文档之前运行脚本 - 请查看<script> {em>} <{1}}及其<body>上的<button>

为脚本标记提供defer属性:

<script defer src="..

或将其移至身体的底部:

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

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

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