代码之家  ›  专栏  ›  技术社区  ›  00Saad

JavaScript:当我已经有onclick事件时,如何添加keypress事件?

  •  0
  • 00Saad  · 技术社区  · 8 年前

    当用户单击按钮时,它可以正常工作,但我也希望用户按下这些键。我不知道怎样才能顺利地做到这一点。

    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);
        });
    };
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Scott Marcus    8 年前

    .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>
    推荐文章