单击侦听器会触发两次

时间:2018-04-08 07:43:57

标签: javascript arrays click addeventlistener

我正在创建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是一个布尔值,用于在计算机转动时停止点击监听器。

1 个答案:

答案 0 :(得分:1)

理想情况下,当您完成事件监听器或将其置于sql.all(`SELECT * FROM '${message.guild.id}'`).then(function(rows){ rows.forEach(function (row) { console.log(row); }); }).catch(function(err){ console.error(err); }); 之外时,它会删除事件监听器,但这是一个快速解决方法:

使用game()代替.onclick,这将覆盖原始版本而不是在调用addEventListener时添加其他事件,您可以在其他位置使用game()来检查是否element附加了一个事件if(colors.children[i].onclick)

PEN中的第157行变为:onclick

并删除第204行的colors.children[i].onclick = function(e) {

&#13;
&#13;
)
&#13;
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');
&#13;
&#13;
&#13;

相关问题