随机数游戏不起作用

时间:2019-05-08 14:52:38

标签: javascript html

我只需要一些简单代码的帮助,我想可能是我的身份证,但我不确定,因此任何帮助都会有用。

<script>
  function guessNumber() {
    var playerGuess = document.getElementById("guessInput").value;
    var computerChoice = Math.floor(Math.random() * 10) + 1;
    if (playerGuess == computerChoice) {
      document.getElementById("output").innerHTML = "You win: both you and 
      the computer picked "+playerGuess;
    } else {
      document.getElementById("output").innerHTML = "Too bad,  you picked “  +
        playerGuess + " and the computer picked " + computerChoice;
    }
</script>
</head>

<body>

  <h1>Guessing Game
    <h1>
      <br>
      <h2>The computer will choose a number between 1 and 100
        <h2>
          <br>
          <h2>You have to try and guess what it picked
            <h2>
              <br>
              <span>Input your guess</span>
              <input id="guessInput">
              <br>
              <button onclick="guessNumber()">Guess</button>
              <p id="output"></p>

2 个答案:

答案 0 :(得分:1)

您有一些语法错误。除此之外,它工作正常:

  • 第6行需要用引号引起来,第7行需要用引号引起来
    • document.getElementById("output").innerHTML = "You win: both you and the computer picked "+playerGuess;成为document.getElementById("output").innerHTML = "You win: both you and " "the computer picked "+playerGuess;
  • 第9行需要正确的双引号,而不是“”字符
    • document.getElementById("output").innerHTML = "Too bad, you picked “成为document.getElementById("output").innerHTML = "Too bad, you picked "
  • 第12行需要使用右括号括住您的功能guessNumber()
    • 应该为function guessNumber() { <your code> }而不是function guessNumber() { <your code> ...没有右括号

答案 1 :(得分:0)

首先,您的JS函数未使用右括号}正确关闭,从而导致语法错误。其次,您有一个代码不支持的字符双引号,而不是使用",这也会导致运行时错误。另外,您不会关闭标题标签(<h1>, <h2>)等。

function guessNumber() {

  var playerGuess = document.getElementById("guessInput").value;
  if (playerGuess == "" || playerGuess < 1 || playerGuess > 100) {
    document.getElementById("output").innerHTML = "Please enter a number 1 - 100";
    return;
  }

  var computerChoice = Math.floor(Math.random() * 10) + 1;

  if (playerGuess == computerChoice) {
    document.getElementById("output").innerHTML =
      "You win: both you and the computer picked " + playerGuess;
  } else {
    document.getElementById("output").innerHTML =
      "Too bad,  you picked " + playerGuess + " and the computer picked " + computerChoice;
  }

}
<h1>Guessing Game
</h1>
<br/>
<h2>The computer will choose a number between 1 and 100
</h2>
<br/>
<h2>You have to try and guess what it picked
</h2>
<br/>
<span>Input your guess</span>
<input type="number" min="1" max="100" id="guessInput" />
<br/>
<button onClick="guessNumber();">Guess</button>
<p id="output"></p>