首页 > 解决方案 > 定时器功能不以事件监听器开始

问题描述

我正在尝试制作一个游戏,一旦用户单击“开始”,计时器将启动,用户将被重定向到新页面。

到目前为止,用户被重定向到一个新页面,但计时器功能没有倒计时。我的控制台日志显示错误

script.js:20 未捕获的类型错误:无法在 HTMLDocument 中读取 null 的属性“addEventListener”。(script.js:20)

这是js代码

document.addEventListener('DOMContentLoaded', () => {
    const timeLeftDisplay = document.querySelector("#timer");
    const beginbtn = document.querySelector("#beginBtn");

    let secondsLeft = 45

    function countDown(){
        window.location.href = "questions.html"
        setInterval(function(){

            if (secondsLeft <= 0) {
                clearInterval(secondsLeft)
                window.location.href = "https://twitter.com"
            }
            timeLeftDisplay.innerHTML = timeLeftDisplay
            secondsLeft -=1

        },1000)
    }
    beginbtn.addEventListener('click', countDown)
})

这是用户将被重定向到的 HTML 页面

 <body>
    <header class="container mt-5">
        <div class = "row justify-content-end">
            <h6>time:</h6>
            <h6 id = "timer"></h6>
        </div>
      <div class="row justify-content-center">
        <div class="col">
          <h1 class="text-center">questions</h1>
        </div>
      </div>
    </header>
    <main>
      <div class="container mt-5">
        <div class="row justify-content-center">
          <h6 id = "question"></h6>
        </div>
        <div class="row justify-content-center mt-2" id = questionContain>
          <button type="button" class="btn btn-outline-info btn-lg" id = "choiceOne">
           
          </button>
        </div>
      </div>
    </main>
</body>

这是带有开始按钮的主页

  <main>
      <div class="container">
        <div class="row justify-content-center">
          <div>
            <button
           
              type="button"
              class="btn btn-outline-info btn-lg"
              id="beginBtn"
            >
              Begin
            </button>
          </div>
        </div>
      </div>
    </main>

标签: javascripthtml

解决方案


更改timeLeftDisplay.innerHTML = timeLeftDisplaytimeLeftDisplay.innerHTML = secondsLeft;移入window.hrefif 函数。并添加元素id="timer"。还要在每个语句后添加;分号


推荐阅读