简体   繁体   中英

jQuery using keydown/keyup/keypress event to fire only one time instead of multiple times when key held down

I'm trying to add the same div with same class after the first one on each keypress on the board.

  1. 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.

<div class="player1"></div>

$(document).on('keydown', function() {
    $('.player1:last').after('<div class="player1">Go!<div>');
})
  1. 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.

You can use .one() to attach keydown event, at keyup event re-attach keydown event using .one() again, which should prevent keydown handler from being called when key is held down.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM