我正在创建 Simon 游戏作为 Freecodecamp 挑战,我完成了基本的事情,现在我正在努力重置游戏。我有一个重置它的功能,清除数组、超时等。
问题是当我再次点击开始按钮开始新游戏时,它会重置,开始新游戏,但点击颜色会触发玩家数组中的颜色两次。
这是一些代码:codepen
function reset() {
clearTimeout(repeating);
clearTimeout(genColor);
pickedColors = []; // computer random colors
guessingColors = []; //colors that player picks, should match picked ones
gameOn = false;
countNumber = 0;
}
function game() {
// Counting
console.log(pickedColors, guessingColors);
counter.innerHTML = countNumber;
// New color
genRandom = setTimeout(() => {
getRandomColor();
}, 5);
guessingColors = [];
// Add click listener for each color
for(let i=0; i<colors.children.length; i++) {
// Guessing
colors.children[i].addEventListener("click", function(e) {
if(!running) {
// Add clicked color to user clicked array
guessingColors.push(this);
console.log(guessingColors);
// Add animation class
clickClass(this);
} else {
e.stopPropagation();
}
// repeating.....
running
是一个 bool 值,用于在计算机启动时停止点击监听器。
最佳答案
理想情况下,当您完成事件监听器或将其放在 game()
之外时,它会删除事件监听器,但这里有一个快速修复:
使用 .onclick
而不是 addEventListener
,当 game()
被调用时,这将覆盖原来的而不是添加另一个事件,你可以在别处使用 if(colors.children[i].onclick)
来检查元素是否有事件 onclick
附加到它。
您的 PEN 中的第 157 行变为:colors.children[i].onclick = function(e) {
并删除第 204 行的 )
document.querySelector('#btn').onclick = function() {
console.log('here');
};
document.querySelector('#btn').onclick = function() {
console.log('hello'); // this will overwrite the first one
};
if (document.querySelector('#btn').onclick)
console.log('it has an event listener');
else
console.log('it does not');
<button id="btn">Click me</button>
关于javascript - 点击监听器触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715621/