简体   繁体   中英

How to get a key press to correspond to the function that gets called first in javascript

So I'm trying something out, if you have two functions you want to call after the same key press like so:

    var plus = function () {
    document.addEventListener("keyup", function(e) {
        if (/[+]/g.test(e.key)) {
            console.log("plus");
        }
    })
    }

    plus();

    var minus = function() {
        document.addEventListener("keyup", function(e) {
            if (/[-]/g.test(e.key)) {
                console.log("minus");
            }
        });
    }

    minus();

    function check() {
        document.addEventListener("keyup", function(e) {
            if(plus) {
                if (e.keyCode == 13) {
                    console.log("enter pressed after plus");
                    plus = false;
                    minus = function() {
                        document.addEventListener("keyup", function(e) {
                            if (/[-]/g.test(e.key)) {
                                console.log("minus");
                            }
                        });
                    }
                }
            } else if(minus) {
                if (e.keyCode == 13) {
                    console.log("enter pressed after minus");
                    minus = false;
                    plus = function () {
                        document.addEventListener("keyup", function(e) {
                            if (/[+]/g.test(e.key)) {
                                console.log("plus");
                            }
                        })
                    }
                }

            }
        });
    }

    check();

If you press minus first then enter console.log("enter pressed after plus") always gets called first because of the code's order, even though what I want to do is that I want the enter to correspond to the key I'm pressing first, if I press plus first then I want console.log("enter pressed after plus") to get called, and if I press minus first then I want console.log("enter pressed after minus") to get called.

Any help would be appreciated and thanks in advance.

Oh also sorry about the stupid title, couldn't think of a better one.

To clean this up a bit (keep it DRY ) you can move all the event handler logic into a single function and use a single listener.

To keep track of the last pressed key we can use a variable defined in the function's outer scope . And, update it after each event. Then, when "Enter" is pressed we can check what the last key was and log accordingly.


Also, the KeyboardEvent.keyCode property is depreciated. You should use KeyboardEvent.code property instead.


Example

 const input = document.querySelector('input') const log = document.getElementById('log') function check() { let lastKey = null input.addEventListener('keyup', ({ key }) => { if (['+', '-', 'Enter'].includes(key)) { // we only care about these keys if (key === '+') log.textContent = 'plus' if (key === '-') log.textContent = 'minus' if (key === 'Enter') { // `Enter` was keyed, what was keyed last? if (lastKey === '+') log.textContent = 'enter pressed after plus' if (lastKey === '-') log.textContent = 'enter pressed after minus' } lastKey = key // current key becomes last key } }) } check()
 <input placeholder="Click here, then press and release a key." size="40"> <p id="log"></p>


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