重置字段后,我不断收到Uncaught TypeError

时间:2019-03-08 23:09:54

标签: javascript html5 dom

我正在创建一个数字猜谜游戏。 当我运行游戏时,该功能有效,但是当我通过单击重置按钮重置游戏时,我不断得到:

script.js:39 Uncaught TypeError: Cannot set property 'innerHTML' of null
at HTMLButtonElement.guessToUI

我已经用类似类似的问题扫描了StackOverflow页面,但是我无法找到针对我的问题的明确解决方案。任何帮助将不胜感激!预先感谢!

var actualNum = randomNumber();

function randomNumber() {
  return Math.floor(Math.random() * 101);
}

function findCorrectGuess(actualNum, userGuess) {
  if (userGuess > actualNum) {
    return "That is too high!"
  } else if (userGuess < actualNum) {
    return "That is too low!"
  } else if (userGuess === actualNum) {
    return "BOOM!"
  }
}

function reset() {
  document.getElementById('input').value = "";
  document.getElementById('player-guess').remove();
  listeners();
}

function clearField() {
  document.getElementById('input').value = "";
}

function guessToUI() {
  let userGuess = document.getElementById('input').value;
  document.getElementById('player-guess').innerHTML = `<center><h1>Your last guess was</h1><h2>${userGuess}</h2><h3>${findCorrectGuess(parseInt(actualNum),parseInt(userGuess))}</h3></center>`
}

function listeners() {
  document.getElementById('guesser').addEventListener('click', guessToUI);
  document.getElementById('clear').addEventListener('click', clearField);
  document.getElementById('reset').addEventListener('click', reset);
}

listeners();
<header>
  <h1>
    <center><span id="num">Number</span> <span id="guess">Guesser</span></center>
  </h1>
</header>
<div class="center-block">
  <input id="input" type="number" name="fname" placeholder="Enter your guess"><br>
  <button id="guesser" class="btn">Guess</button>
  <button id="clear" class="btn">Clear</button>
  </form>
</div>

<div id="player-guess">

</div>

<footer class="bottom">
  <button id='reset' class="btn">Reset</button>
</footer>

1 个答案:

答案 0 :(得分:1)

您要在重置时删除DOM元素:

document.getElementById('player-guess').remove();

试试看

document.getElementById('player-guess').innerHTML = '';