简体   繁体   中英

“keyup” event and “keydown” being called by the same event handler

Hope your having a wonderful week:D

I have just started up with JavaScript and was wondering is it possible to handle the two events from one event-handler.

So for example

document.addEventListener("keydown",handleKeys);
document.addEventListener("keyup",handleKeys);
    function handleKeys(e , a){
        switch(e.keyCode) {
           case '0': return isSomething = a; // a = false | true for keydown and keyup
       }
    }

Would something like this be possible

Yes, that's possible, though you'll need to set the 2nd param of handleKeys, or it will be undefined .

document.addEventListener("keydown", e => handleKeys(e, true));
document.addEventListener("keyup", e => handleKeys(e, false));

function handleKeys(e, down) {
  console.log(down);
}

Yes you can do it, however - dont do it in this way - is better to use two separate handlers. If they have shared code, then move that code to separate third method which will be call with that handlers.

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