javascript - 定时器功能不以事件监听器开始
问题描述
我正在尝试制作一个游戏,一旦用户单击“开始”,计时器将启动,用户将被重定向到新页面。
到目前为止,用户被重定向到一个新页面,但计时器功能没有倒计时。我的控制台日志显示错误
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>
解决方案
更改timeLeftDisplay.innerHTML = timeLeftDisplay
并timeLeftDisplay.innerHTML = secondsLeft;
移入window.href
if 函数。并添加元素id="timer"
。还要在每个语句后添加;
分号
推荐阅读
- caching - 设置关联缓存 - 有多少内存块映射到一组?
- ubuntu - Ubuntu - 使用用户输入的顺序文件命名
- c++ - 当我使用 1000 个键值的数据集时出现分段错误,并且由于某种原因,AVL 旋转不会发生在节点周围
- sas - 将数据字典拆分为输入/格式/标签文件时,SAS 导出文件是否有规范?
- python - Raspberry Pi 3 GUI 界面按钮和 LED 灯
- microsoft-graph-api - 扩展和过滤 MS Graph API 不起作用
- spatstat - 在 spatstat 中为锥形点云创建 pp3 点模式
- javascript - 如何修复 phpmyadmin 中的日期错误 0000-00-00?
- c - 使用 GLUT 和 C 编写文本
- javascript - html中的外部javascript文件不起作用