Javascript函数在浏览器中不起作用(但在代码片段中工作正常)

时间:2016-07-13 05:50:08

标签: javascript html function

我是直接从MDN练习但由于某些原因,此代码未在Chrome或IE中运行。单击该按钮时,不会调用该函数。这是一个猜测用户输入的程序,并说明它是对还是错。有人可以告诉我我做错了什么吗?如果你在代码片段中运行它,它可以很好地工作。但由于某些原因,它在浏览器中无法正常工作。

var randomNumber = Math.floor(Math.random() * 100) + 1;

var guesses = document.querySelector(".guesses");
var lastResult = document.querySelector(".lastResult");
var lowOrHi = document.querySelector(".lowOrHi");

var guessSubmit = document.querySelector(".guessSubmit");
var guessField = document.querySelector(".guessField");

var guessCount = 1;
var resetButton;


function checkGuess() {

  var userGuess = Number(guessField.value);
  if(guessCount === 1) {
    guesses.textContent = 'Previous guesses: ';
  }
  guesses.textContent += userGuess + ' ';
 
  if(userGuess === randomNumber) {
    lastResult.textContent = 'Congratulations! You got it right!';
    lastResult.style.backgroundColor = 'green';
    lowOrHi.textContent = '';
    setGameOver();
  } else if(guessCount === 10) {
    lastResult.textContent = '!!!GAME OVER!!!';
    setGameOver();
  } else {
    lastResult.textContent = "Wrong!";
    lastResult.style.backgroundColor = 'red';
    if(userGuess < randomNumber) {
      lowOrHi.textContent = 'Last guess was too low!';
    } else if(userGuess > randomNumber) {
      lowOrHi.textContent = 'Last guess was too high!';
    }
  }
 
  guessCount++;
  guessField.value = '';
  guessField.focus();
}

guessSubmit.addEventListener('click', checkGuess);
	<p class="guesses"> </p>
	<p class="lastResult"></p>
	<p class="lowOrHi"></p>

	<label for="guessField"> Enter a guess: </label> <input type="text" id="guessField" class="guessField">

	<input type="submit" value="Submit guess" class="guessSubmit">

0 个答案:

没有答案