我的loadgame()中有一个addEventListener,每当我点击newgame按钮,它就会启动loadgame(),但loadgame()中没有返回值,所以每次我点击newgame按钮,它都会重新启动游戏,但模板[i]的eventListeners似乎重叠,所以如果我点击newgame 10次,则点击循环的else语句,它将运行tryagain()10次。我如何退出我在玩NeGAME游戏时的功能?我试图在loadGame()的末尾添加一个return语句,但这没有起到任何作用。
newGame.addEventListener('click', function(){
changeDifficulty();
});
function changeDifficulty(){
loadGame();
}
loadGame()中的循环
for (var i = 0; i < template.length; i++) {
//add colors to squares
template[i].style.backgroundColor = colors[i];
template[i].addEventListener('click', function(){
var clickedColor = this.style.backgroundColor;
if(clickedColor === correctColor) {
clearInterval(timeout);
message.innerHTML = "Correct!";
newGame.textContent = "Play Again?";
}
else {
fails++;
tryAgain(difficulty);
this.style.backgroundColor = "#232323";
message.innerHTML = "Wrong!"
}
});
最佳答案
在注册新的事件侦听器之前,您需要删除这些事件侦听器:
function loadGame() {
// <...>
for (var i = 0; i < template.length; i++) {
//add colors to squares
template[i].style.backgroundColor = colors[i];
template[i].addEventListener('click', clickHandler);
}
// <...>
}
function changeDifficulty() {
// remove all event listeners
for (var i = 0; i < template.length; i++) {
template[i].removeEventListener('click', clickHandler);
}
// Then call loadgame
loadGame();
}
function clickHandler(e) { // We need to be able to reference this function by name
var clickedColor = e.target.style.backgroundColor;
if(clickedColor === correctColor) {
clearInterval(timeout);
changeColorsOnWin(correctColor, template);
message.innerHTML = "Correct!";
newGame.textContent = "Play Again?";
}
else {
fails++;
tryAgain(difficulty);
this.style.backgroundColor = "#232323";
message.innerHTML = "Wrong!"
}
}
关于javascript - 如何在再次调用之前结束函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45954091/