HTML键盘的JavaScript事件的简洁处理

ukxgm1gy  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(101)

我已经创建了一个html键盘,如下所示。我正在寻找一种简单的方法来创建一个单一的事件处理程序,检测哪个数字被点击,然后将数字或文本值传递给一个单独的函数,更新文本显示。如果可能的话,我宁愿使用纯JavaScript,即没有jQuery。

<div id="numbers">
        <a class='r1'>1</a>
        <a class='r1'>2</a>
        <a class='r1'>3</a>
        <a class='r2'>4</a>
        <a class='r2'>5</a>
        <a class='r2'>6</a>
        <a class='r3'>7</a>
        <a class='r3'>8</a>
        <a class='r3'>9</a>
        <button type="button" id="buttonCancel">Cancel</button>
        <a class='r4'>0</a>
        <button type="button" id="buttonOk">OK</button>
</div>
wlzqhblo

wlzqhblo1#

您是否正在寻找类似this的内容?

function init() {
    // Solution 1
    /*var numberEls = document.getElementsByClassName('number'),
          displayLabel = document.getElementById('display-label'),
          numberClickHandler = function(e) {
              var number = e.target.innerHTML;

              otherFunction(parseInt(number));
          },
          otherFunction = function(n) {
              displayLabel.innerHTML = n;
          };

    for (var i = 0; i < numberEls.length; i++) {
        var elem = numberEls[i];

        if (elem.addEventListener) {
            elem.addEventListener('click', numberClickHandler, false);
        }
        else if (elem.attachEvent) {
            elem.attachEvent('onClick', numberClickHandler);
        }
    }*/

    // Solution 2
    var numbers = document.getElementById('numbers'),
        displayLabel = document.getElementById('display-label'),
        numberClickHandler = function(e) {
            var number = e.target.innerHTML;

            // Supress clicks on cancel or ok buttons.
            if (e.target.id == 'buttonCancel' || e.target.id == 'buttonOk')
                return false;

                otherFunction(parseInt(number));
            },
            otherFunction = function(n) {
                displayLabel.innerHTML = n;
            };

    if (numbers.addEventListener) {
        numbers.addEventListener('click', numberClickHandler, false);
    }
    else if (numbers.attachEvent) {
        numbers.attachEvent('onClick', numberClickHandler);
    }  
}

相关问题