我正在制作打字游戏。当多个玩家玩游戏时,它会再次运行同一组功能。我使用变量j作为计数器来在正确输入单词时使单词前进。出于某种原因,在每次upkeystroke的第二次传递中,它记录j = 1& j =无论先前球员最后一个单词+1的值是多少。当每个玩家都玩时,我希望他们输入的每组单词都是相同的,这样才是公平的。我无法弄清楚为什么会发生这种情况,甚至不知道变量如何同时具有2个值?!?!?
是什么给出了?
这里是有问题的代码,但是可能涉及一堆回调,尽管这个变量被调用的唯一地方就在这个函数中。
//advances ship on correct typing
function runRace() {
timer();
var j = 1;
//BUG HERE !! Works fine on first iteration but on second
//iterations value jumps beteween 1 and whatever the next
//one is. It's like on every keystroke it reassigns var j
//back to 1, then back to the element number it was on
//last time
//!!! j has 2 values !!!it's keeping the value from the
//prior running of run race
$(document).keyup(function(e){
var targetWord = $(".toType").text();
var typedWord = $("#word").val();
//while (j < gameWords.length){
console.log("j = " + j);
if(typedWord === targetWord){
$(".player").css({left: "+=15px",});
targetWord = $(".toType").text(gameWords[j]);
$("#word").val("");
j++;
}else {
return
};
//}
});
}
如果您需要查看剩下的代码来解决这个问题,请点击此处。虽然它没有在jsfiddle上正常运行,但它在本地https://jsfiddle.net/ujsr139r/1/
之外的其他方面起作用了答案 0 :(得分:1)
正如我在评论中提到的那样,每次调用runRace()
时都会创建多个侦听器。
你可以尝试这样的事情(请注意,这不是最好的方法,我只是在演示。在这种情况下,像j
这样的全局变量不是&#39;聪明的想法。:
var j=1; // global because its outside of your function
$(function(){
$(document).keyup(function(e){
var targetWord = $(".toType").text();
var typedWord = $("#word").val();
//while (j < gameWords.length){
console.log("j = " + j);
if(typedWord === targetWord){
$(".player").css({left: "+=15px",});
targetWord = $(".toType").text(gameWords[j]);
$("#word").val("");
j++;
}else {
return
};
//}
});
});
//advances ship on correct typing
function runRace() {
j = 1;
timer();
}