我在教自己編程。幾天前我剛剛在JS開始了一個Hang子手遊戲。我無法弄清楚用戶點擊的列表值是否是他們試圖猜測的單詞中的一個值。我認爲這是一個「全局和局部變量」的問題,但我不確定如何避免在一個函數中包含所有內容。我的代碼如下,對於noob錯誤感到抱歉,我非常感謝任何能夠給我一點建議的人。謝謝!第一次編程遊戲的問題(javascript/jQuery)
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!");
}
});
}
'word'不超出範圍的點擊功能,如果這是你是什麼擔心。究竟發生了什麼?你能顯示相關的dom嗎? – smerny
在發佈之前,您應該檢查點擊功能的API文檔。嘗試使用Google搜索。 –
那麼你現在的代碼有什麼問題? – Doorknob