我正在构建一个简单的JS游戏,但++不断加起来。 这是代码:
var cities = ["Atlanta","Chicago","Honolulu","Houston","Nashville","Orlando","Philadelphia","Phoenix","Portland","Seattle"],
c = Math.floor((Math.random() * 10)),
city = cities[c].toUpperCase(),
cityArr = city.split(""),
length = city.length,
guess = 0,
$prompt = $('#prompt'),
x, //letter guess
i;
function randomCity() {
var $showCity = document.getElementById("showCity"), //ul
newLi,
letter;//each letter of city
for(i=0; i<cityArr.length; i++){
newLi = document.createElement("li");
$showCity.appendChild(newLi);
letter = document.createTextNode(cityArr[i]);
newLi.appendChild(letter);
}
$("#showCity li").css("color", "#fff");
}//end randomCity()
function play() {
if(guess == 6){
$("#alphabet").css("visibility", "hidden");
ending();
} else {
$prompt.fadeIn("slow").text("Guess a letter: ");
guessLetter();
}
} // end play function
function guessLetter() {
var showLetter;
guess++
console.log(guess); //SHOWS THE COUNTER ADDING UP CONTINUOUSLY AFTER 2
$("#alphabet li").on('click', function () {
$(this).css("visibility", "hidden");
x = this.id;
if (city.indexOf(x) == -1) {
$prompt.fadeIn("slow").text("No letter " + x);
setTimeout(play, 1500);
} else {
for (i = 0; i < length; i++) {
if (city[i] == x) {
$prompt.fadeIn("slow").text("There is letter " + x + "!");
showLetter = "#showCity li:nth-child("+(i+1)+")";
$(showLetter).css("color", "#0F9ED8");
}
} //for loop
setTimeout(play, 1500);
} //else
});
}
function ending(){ //STILL IN PROGRESS
var guessWord,
finalOutput;
$prompt.fadeIn("slow").text("What is the word? ");
//guessWord = word from input
finalOutput = (guessWord == city) ? "That is correct!" : "Sorry, that is wrong.";
$prompt.fadeIn("slow").text(finalOutput);
}
$(document).ready(function(){
$("#start").on('click', function() {
$(this).hide();
randomCity();
console.log(city);
$("#alphabet").css("visibility", "visible");
play();
});
}); // end ready
单击第二个元素后,变量guess(计数器)的值为4,单击第3个元素后,其值为6。我在我的代码的不同部分移动了var猜测,但它仍然在做。这很奇怪!
答案 0 :(得分:1)
通过
for (String title : books) {
System.out.println(" " + title);
}
每次$("#alphabet li").on('click', function () { /* ... */}`
函数执行时,您都会绑定一个新的点击处理程序。多个点击处理程序会调用guessLetter()
函数,该函数会再次调用play()
函数,导致guessLetter()
多次递增。
仅将点击处理程序绑定一次。
答案 1 :(得分:1)
每次调用guessLetter
函数时,都会在列表项中附加新的点击处理程序。
要修复它,您可以将guessLetter
中的所有内容移动到您的console.log调用后发生在$(document).ready
回调函数中。