代码之家  ›  专栏  ›  技术社区  ›  merko

单击侦听器激发两次

  •  3
  • merko  · 技术社区  · 7 年前

    我正在创建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 回复  |  直到 7 年前
        1
  •  4
  •   Taki    7 年前

    理想情况下,可以在使用完事件侦听器后将其删除,或者将其放在 game() 但这里有一个快速修复方法:

    使用 .onclick 而不是 addEventListener ,这将覆盖原始事件,而不是在以下情况下添加另一个事件 游戏() 调用,您可以使用 if(colors.children[i].onclick) 检查元素是否有事件 onclick 附加到它。

    笔中的第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>