javascript - 代码返回相同的Uncaught TypeError : Cannot read property 'addEventListener' of null

标签 javascript error-handling

我遇到问题,我试图创建一个按钮,当按下true按钮时,该按钮会记录正确答案+1,但每次都会收到相同的错误“Uncaught TypeError:无法读取null的属性'addEventListener'”。我认为这是因为代码是在创建按钮之前运行的,但是我无法弄清楚如何解决它,对您有所帮助,请看困惑的代码

window.onload = function () {
  var content = document.querySelector(".welcome");
  var button = document.querySelector(".start");
  var mainDiv = document.querySelector("#main");
  var timer = document.querySelector(".timer");
  var title = document.querySelector("h1");
  var flaseB1 = document.querySelector(".flaseB1");
  var trueB1 = document.querySelector(".trueB1");

  console.log(title);
  console.log(content);
  console.log(button);
  console.log(mainDiv);

  var secondsLeft = 30;

  button.addEventListener("click", function () {
    this.style.display = "none";
    setTime();
    firstQuestion();

    function setTime() {
      var timerInterval = setInterval(function () {
        secondsLeft--;
        timer.textContent = secondsLeft;

        if (secondsLeft === 0) {
          clearInterval(timerInterval);
          sendMessage();
        }
      }, 1000);
    }

    function sendMessage() {
      timer.textContent = "Time is UP!";
    }

    setTime();

    function firstQuestion() {
      title.textContent = "Question #1";
      content.textContent = "Hippos are blue";
      createButtons();
    }

    function createButtons() {
      var trueB1 = document.createElement("button");
      trueB1.textContent = "Ture";
      trueB1.setAttribute("class", ".trueB1");
      mainDiv.appendChild(trueB1);
      console.log(trueB1);

      var flaseB1 = document.createElement("button");
      flaseB1.textContent = "False";
      flaseB1.setAttribute("class", "flaseB1");
      mainDiv.appendChild(flaseB1);
      console.log(flaseB1);
    }

    var correctAnswers = 0;
    var incorrectAnswers = 0;

    trueB1.addEventListener("click", createButtons, function () {
      correctAnswers++;
    });

    flaseB1.addEventListener("click", function () {
      incorrectAnswers++;
    });
  });
};

这是HTMl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="hw.css">

</head>
<body>

    <div id="main">
   <h1> Coding Quiz Challenge! </h1> 
   <p class="welcome"> Press the start button to begin </p>
    <button class="start"> Start </button>
    </div>

    <div class="top">
    <p class="timeleft"> Time left (seconds):</p> 
    <p class="timer"> 30 </p>
    </div>

   <script type="text/javascript"  src="hw.js" charset="utf-8"></script>
</body>
</html>

最佳答案

这是变量作用域的问题,我建议对逻辑要更直接一点。另外,其中一个按钮的名称错误,并且eventListener困惑。

var content = document.querySelector(".welcome"),
    button = document.querySelector(".start"),
    mainDiv = document.querySelector("#main"),
    timer = document.querySelector(".timer"),
    title = document.querySelector("h1");

function setTime() {
  // global w/o `var` keyword
  secondsLeft = 30;

  var timerInterval = setInterval(function() {
    secondsLeft--;
    timer.textContent = secondsLeft;

    if (secondsLeft === 0) {
      clearInterval(timerInterval);
      sendMessage();
    }
  }, 1000);
}

function createButtons() {
  // make global
  trueB1 = document.createElement("button");
  trueB1.textContent = "True";
  trueB1.setAttribute("class", "trueB1");
  mainDiv.appendChild(trueB1);

  // make global
  falseB1 = document.createElement("button");
  falseB1.textContent = "False";
  falseB1.setAttribute("class", "falseB1");
  mainDiv.appendChild(falseB1);
}

function sendMessage() {
  timer.textContent = "Time is UP!";
}

function firstQuestion() {
  title.textContent = "Question #1";
  content.textContent = "Hippos are blue";
  createButtons();
}

button.addEventListener("click", function() {

  this.style.display = "none";
  setTime();
  firstQuestion();

  var correctAnswers = 0;
  var incorrectAnswers = 0;

  trueB1.addEventListener("click", function() {
    correctAnswers++;
    console.log({ correctAnswers });
  });

  falseB1.addEventListener("click", function() {
    incorrectAnswers++;
    console.log({ incorrectAnswers });
  });

});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="hw.css">

</head>

<body>

  <div id="main">
    <h1> Coding Quiz Challenge! </h1>
    <p class="welcome"> Press the start button to begin </p>
    <button class="start"> Start </button>
  </div>

  <div class="top">
    <p class="timeleft"> Time left (seconds):</p>
    <p class="timer"> 30 </p>
  </div>
</body>

</html>

关于javascript - 代码返回相同的Uncaught TypeError : Cannot read property 'addEventListener' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62354312/

相关文章:

javascript - 在捕获之前编辑抛出的错误?

c# - facebox不是asp.net主页中的功能

javascript - Angular 模板仅从 MeteorJS 的根目录加载

javascript - Cognito adminDeleteUser 用户池不存在错误

javascript - 防止 iframe 加载响应式设计

error-handling - pk = request我有一些错误。由于出现此错误,我似乎无法将我的储备金链接到另一页

android - 在覆盖DefaultUncaughtExceptionHandler的同时,我还能在市场上获得错误报告吗?

javascript - 为图像模式选择多个元素

javascript - 我们可以在json数据文件中添加图像并使用D3.js在页面上调用它吗

windows - 错误 1053 : the service did not respond to the start or control request in a timely fashion