已有onclick事件,如何添加按键事件?

问题描述 投票:0回答:1

我正在构建一个网络计算器。

当用户点击按钮时,它工作得很好,但我也希望用户按下按键。我不知道如何顺利地做到这一点。

我只包含了我的程序的事件监听器部分,因为其他部分对我的问题来说是不必要的。

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);
    });
};
javascript onclick dom-events addeventlistener keypress
1个回答
1
投票

你现在的代码使用了一个匿名函数作为点击事件的回调,因为是匿名的,所以你不能在不重复的情况下,把它也重用在其他事件上。所以,把你的回调函数分离出来,并给它一个名字。然后,只需使用第二个 .addEventListener() 并将其(和第一个)指向同一个函数。

下面是一个例子:

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>
© www.soinside.com 2019 - 2024. All rights reserved.