计数器增加两次

Mur*_*son 2 javascript

我正在编写一个简单的JavaScript游戏,其中用户点击播放声音的div,如果他们猜测动物声音是正确的,则计数器会跟踪他们的分数和增量.
它可以工作,但如果再次播放相同的声音并且用户猜测它会使计数器增加两个而不是一个,有时甚至三个,我无法弄清楚为什么以及如何修复它,这是我的HTML:

<div id="counter">Score:<span id="counter-score"> 0</span> </div>
Run Code Online (Sandbox Code Playgroud)

这是JavaScript代码:

var sounds = [
    {
        animalType: 'horse',
        sound: new Audio('../sounds/Horse-neigh.mp3')
    },
    {
        animalType: 'bear',
        sound: new Audio('../sounds/grizzlybear.mp3')
    },
    {
        animalType: 'goat',
        sound: new Audio('../sounds/Goat-noise.mp3'),
    }
];

var player = document.getElementById('player');
var enteredWord = document.getElementById('entered-word');
var counter = document.getElementById('counter-score');

startGame();


function startGame() {
    player.addEventListener('click', function() {
        var sound = sounds[Math.floor(Math.random() * sounds.length)];
        var currentSound = sound.animalType;
        sound['sound'].play();

        enteredWord.addEventListener('keydown', function() {
            if (event.key === 'Enter') {
                if (enteredWord.value === currentSound) {
                    counter.textContent++;
                }
            } else {

            }
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

我尝试使用+ =运算符,但它给出了相同的结果.

Leo*_*Leo 5

正如@Ibu在评论中所说,每次发生click事件时,都会向keydown事件添加一个新的事件监听器.

您应该在回调enteredWord.addEventListener之外提取部分player.addEventListener,如下所示:

function startGame() {
  var currentSound;
  player.addEventListener('click', function() {
    var sound = sounds[Math.floor(Math.random()*sounds.length)];
    currentSound = sound.animalType;
    sound['sound'].play();
  })


  enteredWord.addEventListener('keydown', function() {
    if(event.key === 'Enter') {
      if(enteredWord.value === currentSound) {
        counter.textContent ++;
      }
    }
  })
}
Run Code Online (Sandbox Code Playgroud)