javascript - 如果存在具有该 id 的 div,为什么我得到 id 为空?
问题描述
我正在尝试执行一个计时器,当它达到零时,整个屏幕变为空白,并带有 a document.body.innerHTML = ""
,之后,我创建了一个<div>
带有标签的标签,其中的文本在 DOM 中的 id中显示<h1>
“Game Over” 。一切都很好,除了我需要将我创建的部分附加到 DOM 中的部分。在调试它之后,它说结果是空的,这没有意义,因为我已经用适当的 id 创建了。<div>
"game____overdiv"
<div>
<div>
const timer = {
sec: 5,
startTimer() {
const timeInterval = setInterval(() => {
const minText = `${Math.floor(this.sec / 60)}`;
const secText = `0${this.sec % 60}`.slice(-2);
document.getElementById('gameTimer').innerHTML = `${minText}:${secText}`;
if (this.sec <= 0) {
clearInterval(timeInterval);
document.getElementById('gameTimer').innerHTML = "Time's up!";
audioHandler.gameOver();
}
if (this.sec <= 0) {
document.body.innerHTML = ""
const div = document.createElement("div")
const text = document.createElement("h1")
const newContent = document.createTextNode("Game Over")
const result = document.getElementById("game____overdiv")
div.appendChild(text)
text.appendChild(newContent)
result.appendChild(div)
console.log(div)
console.log(result)
}
this.sec -= 1;
if (this.sec <= 5 && this.sec > 0) {
audioHandler.startTimeWarning();
} else {
audioHandler.stopTimeWarning();
}
}, 1000);
},
timerAnswerHandling(typeOfAnswer) {
if (typeOfAnswer === 'correct') {
this.sec += 5;
} else if (typeOfAnswer === 'wrong') {
this.sec -= 5;
}
},
levelupHandling() {
this.sec += 20;
},
};
解决方案
推荐阅读
- python - 一行包含十六进制的字节:如何转换为字符串
- python - 在 Python 中使用元素树解析 XML
- javascript - 如何在javascript中使用数组字典?
- networking - 无法从某些 vps 而不是其他 vps 访问 websocket 服务器?
- javascript - Webpack - 使用不同的 javascript 脚本文件生成多个 HTML 文件
- python - 未满足我的 While 循环条件
- r - 尝试提取州缩写
- javascript - 为每个类实例添加类到父 div
- c++ - 为什么我的“Cout”声明打印出随机的东西
- c++ - gai_cancel() 需要很长时间才能成功