javascript - 为什么 onClick 对我的按钮不起作用?

标签 javascript html arrays button onclick

我正在尝试“猜猜!”按钮从我的 JavaScript 文件运行一个函数(创建一个刽子手游戏),但当我单击该按钮时它似乎没有执行任何操作。我已经仔细检查以确保我猜测的是正确的字母,但所有内容仍然显示为下划线。当我在 HTML 页面的按钮中使用 onClick 时,我是否做错了什么?

代码:

//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>

最佳答案

onClick 工作正常,您必须检查 guess 变量的长度,如下所示:

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

您目前的做法是,将一个(可能是空的)字符串与一个数字(0)进行比较,结果可能不是您想象的那样,请参阅 falsytruthy在 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>

关于javascript - 为什么 onClick 对我的按钮不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50010188/

相关文章:

javascript - Angular 4200 端口显示带 html 的数据,但 Nodejs 8080 端口显示不带 html 的 json 数据

javascript - 后效应 : Javascript - Undefined value used in the expression(Could be out of range array subscript)

javascript - 您可以使 javascript 函数在页面上用自定义 html 替换自身吗?

c - 为什么不打印数组?

python - 更快地填写列表

JavaScript 排序数组,但保持第二个数组同步

javascript - 如何从 javascript 函数中显示 Bootstrap 模式?

javascript - 如果屏幕窄于 1280 像素,则隐藏一个 DIV

javascript - 同一按钮的多个实例的标签

html - margin : 0 auto is not centering my image