简体   繁体   中英

How can I add keypress events when I already have an onclick event?

I'm building a web calculator.

It works fine when the user clicks the buttons, but I also want the user to press the keys. I'm not sure how to smoothly do this.

I've only included the event listener portion of my program since the rest of it is unnecessary to my question.

const a = document.getElementsByTagName('input');

// button press conditions
for (let i = 0; i < a.length; i++) {
    a[i].addEventListener('click', function(e) {
        // operators
        if (a[i].value === '+' ||
            a[i].value === '-' ||
            a[i].value === '×' ||
            a[i].value === '÷') {
                prsOpr(i);
        }

        // decimal button
        else if (a[i].value === '.') prsDeci(i);

        // equal button
        else if (a[i].value === '=') prsEql(i);

        // backspace button
        else if (a[i].value === '←') prsBksp();

        // clear button
        else if (a[i].value === 'Clear') prsClr();

        // any number button
        else logNum(i);
    });
};

Your current code uses an anonymous function as the callback to the click event and because it's anonymous, you can't reuse it for other events as well without duplicating it. So, separate your callback function out and give it a name. Then, just use a second .addEventListener() and point it (and the first one) to the same function:

Here's an example:

 let input = document.querySelector("input"); input.addEventListener("click", foo); // Set up a click event handler input.addEventListener("keydown", foo); // Set up a key down event handler // Both event registrations point to this one function as their callback // so, no matter whether you click or type in the field, this function // will run. But, all event handlers are passed a reference to the event // that triggered them and you can use that event to discern which action // actually took place. function foo(evt){ console.log("The " + evt.type + " event has been triggered."); }
 <input>

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