Почему onClick не работает для моей кнопки? - PullRequest
0 голосов
/ 24 апреля 2018

Я пытаюсь получить "Угадай!" кнопка, чтобы запустить функцию из моего файла JavaScript (создание игры палача), но она, похоже, ничего не делает, когда я нажимаю на кнопку. Я дважды проверил, чтобы убедиться, что я угадал правильную букву, но все по-прежнему в подчеркиваниях. Я сделал что-то не так, когда я использовал onClick в кнопке моей HTML-страницы?

КОД:

//create array for words
var listWords = ['cat', 'dog', 'mouse'];

//displays the word in underscores
var hiddenWord = [];

//choose word randomly
//Math.random returns integer between 0 (inclusive) and 1 (exclusive)
//multiply Math.random with the length of the listWords array
//Math.floor rounds down to nearest integer
//note that array indexes start counting from 0, hence why we need to make sure the listWords index never reaches the actual length of the array
var chosenWord = listWords[Math.floor(Math.random() * listWords.length)];

//number of tries the user gets before game over
var lives = 5;

//connected string of underscores that player sees in place of the chosenWord
var answerString;

//function creating underscores to be displayed in place of chosenWord
function hideWord() {
  //for each letter in the chosenWord, replace it with an underscore in the new array
  for (var i = 0; i < chosenWord.length; i++) {
    hiddenWord[i] = '_';
  }
  //joins each underscore (element) of the hiddenWord array into a string with a space in between each
  answerString = hiddenWord.join(' ');

  //return the new string with spaces in between the underscores
  return answerString;
}

function compareLetter() {
  //get the letter that the player typed in the text box
  var guess = document.getElementById("guessedLetter").value;

  //checking to see if player typed a letter
  if (guess > 0) {

    //compare the player input letter to the answer by moving through the chosenWord's array
    for (var i = 0; i < chosenWord.length; i++) {

      //if the player's letter matches one in the chosenWord, then display it
      if (chosenWord[i] === guess) {
        hiddenWord[i] = guess;
      }
    }
    answerString = hiddenWord.join(' ');
    document.getElementById('hiddenWord').innerHTML = answerString;
  }
}


//main function where actions are performed; where the other functions are called
function main() {
  //creating the underscores to hide the chosenWord from the player
  var underscores = document.getElementById("hiddenWord");
  underscores.innerHTML = hideWord();
}
<!DOCTYPE html>
<html>

<head>
  <!--title to appear on the tab of the browser-->
  <title>Midterm: Hangman</title>

  <!--linking a CSS style sheet for the page-->
  <link rel="stylesheet" type="type/css" href="hangman.css">


  <!--running the hangman game-->
  <script src="hangman.js"></script>
</head>

<!--run the main function from the javascript file when page is loaded-->

<body onLoad="javascript:main()">
  <!--adding a title that will appear on the webpage-->
  <h1>Hangman</h1>

  <!--create a text box, restrict to only one letter being able to be typed, create placeholder text-->
  <input id="guessedLetter" type="text" maxlength="1" minlength="1" placeholder="Guess a letter" />

  <!--create a button to submit guessed letter and run the compareLetter function when clicked-->
  <button type="button" onClick="javascript:compareLetter()">Guess!</button>

  <!--underscores to hide the word that the player is guessing-->
  <div id="hiddenWord"></div>

  <!--add instructions for the player-->
  <h2>Instructions</h2>

</body>

</html>

1 Ответ

0 голосов
/ 24 апреля 2018

onClick работает нормально, вы должны проверить длину переменной guess следующим образом:

if (guess.length > 0) {
   // ...
}

То, как вы делаете это в настоящее время, вы сравниваете (возможно, пустую) строку с числом (0), результаты могут быть не такими, как вы думаете, см. falsy и truey в JavaScript.

Примечание. Значение ввода всегда извлекается в виде строки, даже если оно содержит только цифры.

//create array for words
var listWords = ['cat', 'dog', 'mouse'];

//displays the word in underscores
var hiddenWord = [];

//choose word randomly
//Math.random returns integer between 0 (inclusive) and 1 (exclusive)
//multiply Math.random with the length of the listWords array
//Math.floor rounds down to nearest integer
//note that array indexes start counting from 0, hence why we need to make sure the listWords index never reaches the actual length of the array
var chosenWord = listWords[Math.floor(Math.random() * listWords.length)];

//number of tries the user gets before game over
var lives = 5;

//connected string of underscores that player sees in place of the chosenWord
var answerString;

//function creating underscores to be displayed in place of chosenWord
function hideWord() {
  //for each letter in the chosenWord, replace it with an underscore in the new array
  for (var i = 0; i < chosenWord.length; i++) {
    hiddenWord[i] = '_';
  }
  //joins each underscore (element) of the hiddenWord array into a string with a space in between each
  answerString = hiddenWord.join(' ');

  //return the new string with spaces in between the underscores
  return answerString;
}

function compareLetter() {
  console.log('click')
  //get the letter that the player typed in the text box
  var guess = document.getElementById("guessedLetter").value;
console.log(guess);
  //checking to see if player typed a letter
  if (guess.length > 0) {
console.log('yes');
    //compare the player input letter to the answer by moving through the chosenWord's array
    for (var i = 0; i < chosenWord.length; i++) {

      //if the player's letter matches one in the chosenWord, then display it
      if (chosenWord[i] === guess) {
        hiddenWord[i] = guess;
      }
    }
    answerString = hiddenWord.join(' ');
    document.getElementById('hiddenWord').innerHTML = answerString;
  } else {
  console.log('no');
  }
}


//main function where actions are performed; where the other functions are called
function main() {
  //creating the underscores to hide the chosenWord from the player
  var underscores = document.getElementById("hiddenWord");
  underscores.innerHTML = hideWord();
}
<!--run the main function from the javascript file when page is loaded-->

<body onLoad="javascript:main()">
  <!--adding a title that will appear on the webpage-->
  <h1>Hangman</h1>

  <!--create a text box, restrict to only one letter being able to be typed, create placeholder text-->
  <input id="guessedLetter" type="text" maxlength="1" minlength="1" placeholder="Guess a letter" />

  <!--create a button to submit guessed letter and run the compareLetter function when clicked-->
  <button type="button" onClick="compareLetter()">Guess!</button>

  <!--underscores to hide the word that the player is guessing-->
  <div id="hiddenWord"></div>

  <!--add instructions for the player-->
  <h2>Instructions</h2>
</body>
...