gpt4 book ai didi

javascript - 防止 Enter 键不断增加计数器

转载 作者:行者123 更新时间:2023-11-28 17:11:25 24 4
gpt4 key购买 nike

我有一个简单的 JS 应用程序,如果用户猜到了声音,它就会增加计数器。增量有效,但如果用户按住回车键,分数会持续上升,直到他释放该键,我怎样才能避免这种情况,以便他只得一分,如果他尝试在相同的声音上再次按回车键,计数器就会停止添加一点?

我尝试添加一个 boolean 值,但它不起作用,这是我的 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'),
},
{
animalType: 'cat',
sound: new Audio('../sounds/cat.mp3')
},
{
animalType: 'dog',
sound: new Audio('../sounds/dog-bark.mp3')
},
{
animalType: 'sheep',
sound: new Audio('../sounds/sheep.mp3')
},
{
animalType: 'rooster',
sound: new Audio('../sounds/rooster.mp3')
},
{
animalType: 'lion',
sound: new Audio('../sounds/lion.mp3')
},
{
animalType: 'hen',
sound: new Audio('../sounds/hen.mp3')
}
]

var player = document.getElementById('player');
var enteredWord = document.getElementById('entered-word');
var counter = document.getElementById('counter-score');
var errorMessage = document.getElementById('error-message');
var wrongAnswerSound = new Audio('../sounds/Wrong-answer-sound-effect.mp3');
var isEntered = false;

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.toLowerCase() === currentSound && !isEntered) {
counter.textContent ++;
isEntered = true;
errorMessage.style.display = 'none';
enteredWord.classList.remove('input-error-border');
console.log(soundPlayedCount)
} else {
errorMessage.style.display = 'inline-block';
enteredWord.classList.add('input-error-border');
wrongAnswerSound.play();
}
isEntered = false;
}
})
}

startGame();

最佳答案

您放错了以下作业:

isEntered = false;

它应该位于 else block 内。现在,即使您刚刚将 isEntered 设置为 true,它也会使 isEntered 始终为 false。 ;)

我还建议监听 input 事件(而不是 keydown),因为 input 事件也会在输入更改时触发通过鼠标拖放、或通过上下文菜单(例如粘贴)或通过其他输入设备来制作。

关于javascript - 防止 Enter 键不断增加计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54255883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com