【问题标题】:How can I add keypress events when I already have an onclick event?当我已经有 onclick 事件时,如何添加按键事件?
【发布时间】:2018-06-11 15:12:31
【问题描述】:

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

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

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

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);
    });
};

【问题讨论】:

  • 我认为您应该使用一个按钮(例如等号)并在其上设置一个点击监听器,然后在输入上使用 keypressed 事件。
  • 是否可以监听keypress 事件?

标签: javascript onclick dom-events addeventlistener keypress


【解决方案1】:

您当前的代码使用匿名函数作为 click 事件的回调,并且由于它是匿名的,因此您不能在不复制它的情况下将其重用于其他事件。所以,把你的回调函数分开并给它一个名字。然后,只需使用第二个 .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.");
}
&lt;input&gt;

【讨论】:

  • 这个问题太宽泛了?!
  • @JonasW。你在跟我开玩笑吗?它实际上很干。
  • 我想在这种情况下附加两个不同的事件处理程序会更容易。
  • @JonasW。你到底为什么要附加不同的处理程序来做完全相同的事情?
  • 那你能给我看一个减号键的演示吗?就像点击减号按钮一样!
猜你喜欢
  • 2013-12-13
  • 2018-01-09
  • 2021-01-16
  • 2013-07-07
  • 2011-12-21
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多