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

问题描述 投票:0回答:1

我正在创造一个猜数游戏。当我运行我的游戏时,功能有效但当我通过点击重置按钮重置我的游戏时,我会一直得到:

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>
javascript html5 dom
1个回答
1
投票

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

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

试试这个

document.getElementById('player-guess').innerHTML = '';
© www.soinside.com 2019 - 2024. All rights reserved.