-2

我需要编写一个循环,将以下 2 个语句迭代 44 次。

    window.onload = function() {
        var input1 = document.getElementById("alpha1");
        var input2 = document.getElementById("alpha2");
        var input3 = document.getElementById("alpha3");
        input1.onkeypress = alphaFilterKeypress;
        input2.onkeypress = alphaFilterKeypress;
        input3.onkeypress = alphaFilterKeypress;
    };
4

2 回答 2

1

它没有问题:

for (var i = 1; i < 45; i++) {
    var input = document.getElementById("alpha" + i);
    input.onkeypress = alphaFilterKeypress;
}
于 2013-03-25T15:48:05.737 回答
1

与其循环 44 次,不如委派事件?附加单个侦听器,并检查 id 是否与给定模式匹配

document.body.addEventlistener('keypress', alphaFilterKeypress, false);

您必须更改函数定义 - 添加此检查:

function alphaFilterKeypress(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (!target.id.match(/alpha[0-9]+/))
    {//don't handle the event
        //event was fired on an element with another (or no) id
        return e;//don't handle it here
    }
    //an element with id alpha[number] fired the event
    //handle the event
}

正如您从上一个 SO question中看到的那样,您使用的“关键”事件的类型很重要。如果keypress事件不会在退格键、控制键等键上接收到...您可能希望更喜欢使用该keydown事件。
试一试,找出最适合您需求的活动

于 2013-03-25T15:50:44.337 回答