我试图在板上每个按键的第一个之后添加具有相同类的相同 div。
- 使用按键,当用户按住按键时,会导致事件在按住时触发(并继续运行)。我想停止这种情况,并且只在按键时触发该函数一次,即使按住该键也是如此。
<div class="player1"></div>
$(document).on('keydown', function() {
$('.player1:last').after('<div class="player1">Go!<div>');
})
最佳答案
- Using keypress, when the user holds down the key, it causes the event to fire when its held down (and continues to run). I want to stop that and only fire the function once on a keypress even if the key is held down.
您可以使用.one()
附加keydown
事件,在keyup
事件重新附加keydown
再次使用 .one()
事件,这应该可以防止在按住按键时调用 keydown
处理程序。
function handleKeyDown() {
$('.player1:last').after('<div class="player1">Go!<div>');
}
var d = $(document);
d.one('keydown', handleKeyDown)
.on("keyup", function() {
d.one("keydown", handleKeyDown)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="player1"></div>
关于javascript - jQuery 使用 keydown/keyup/keypress 事件在按住按键时仅触发一次而不是多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535002/