我正在自学编程。几天前我刚开始用 JS 玩 Hangman 游戏。我无法确定用户单击的列表值是否是他们试图猜测的单词中的值之一。我认为这是“全局和局部变量”的问题,但我不确定如何在不将所有内容包含在一个函数中的情况下解决它。我的代码如下,对于菜鸟的错误,我非常感谢任何能给我一点建议的人。谢谢!
var wordBank = ['apple', 'orange', 'pear', 'monkey', 'radish'];
var word;
// start game on click and choose random word from wordBank
function startGame() {
$("#hangman").hide('slow');
$("#start").click(function(){
var word = wordBank[Math.floor(Math.random()*wordBank.length)];
var wordLength = word.length;
var underscores = "";
for(i=0; i<wordLength; i++) {
underscores = underscores + "_ "
}
// now variable underscores has the underscores.
$("#word").html(underscores);
});
// get list value for the letter chosen
$(".alpha li").click(function() {
var index = $(this).index();
var text = $(this).text();
// see if character clicked matches index of a letter in the word
if(word.indexOf(text) >= 0) {
alert("Correct Letter!");
} else {
alert("Wrong!");
}
});
}