首页 > 解决方案 > 如果存在具有该 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;
  },
};

标签: javascripthtml

解决方案


推荐阅读