无法更改“点击时” javascript中的文本

时间:2019-06-12 15:30:23

标签: javascript html

我正在用JavaScript做'if,else'语句。我想更改“ h2”文本。我想我缺少一些代码

<div id="game"> 
  <p id="howMany">How many fingers am I holding up?</p> 
  <p id="theGame"> <input type="guess" id="guess" placeholder="0 to 5"> 
    <button id="check-guess"> Guess! </button> 
  </p> 
  <div id="theAnswer"> 
    <h2 id="h2">Your Reward</h2> 
  </div> 
</div>
document.getElementById("check-guess").onclick = function() {
  var randomNumber = Math.random();
  randomNumber = randomNumber * 6;
  randomNumber = Math.floor(randomNumber);
  if (document.getElementById("guess").value == randomNumber) {
    document.getElementsById("h2").innerHTML = "You got it!";
                         } else {
    document.getElementsById("h2").innerHTML = "Nope! Try Again. The number is " +  randomNumber ;
  }
} 

1 个答案:

答案 0 :(得分:2)

您的函数getElementsById不存在,可能是getElementById。您传递的值必须是ID,而不是标记名。

document.getElementById("check-guess").onclick = function() {

  var randomNumber = Math.random();

  randomNumber = randomNumber * 6;

  randomNumber = Math.floor(randomNumber);

  if (document.getElementById("guess").value == randomNumber) {

    document.getElementById("h2").innerHTML = "You got it!";

  } else {

    document.getElementById("h2").innerHTML = "Nope! Try Again. The number is " + randomNumber;
  }
}
<input id="guess">
<button id="check-guess">Check</button>
<h2 id="h2">Test</h2>