Tidier分配Enter Keypress的方式

时间:2012-08-09 08:19:34

标签: javascript jquery

function onLoad() {
    eworkData.FieldByName('SearchReference').HTMLfield.onkeydown=function(evt)
    {
        var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
        if( keyCode == 13 )
        {
            eworkData.FieldByName('cmdSearch').HTMLfield.onfocus();
            eworkData.FieldByName('cmdSearch').HTMLfield.onclick();
        }
    };
    eworkData.FieldByName('SearchFirstName').HTMLfield.onkeydown=function(evt)
    {
        var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
        if( keyCode == 13 )
        {
            eworkData.FieldByName('cmdSearch').HTMLfield.onfocus();
            eworkData.FieldByName('cmdSearch').HTMLfield.onclick();
        }
    };
    // more controls
}

有更简洁的方法吗?更小的紧凑代码?我认为在jQuery中我可以做到

$("SearchReference, SearchFirstName").onkeydown(function() ....)

然而,jQuery对我来说不是一个选择:o(

2 个答案:

答案 0 :(得分:1)

var theElement = document.getElementById("YOUR_ELEMENT");
theElement.addEventListener("keypress", function(e) {
    switch(e.keyCode) {
        case "13":
           //keycode 13 pressed...
           break;
    }
});

或jQuery:

$("YOUR_ELEMENT").live("keypress", function(e) {
   switch(e.keyCode) {

   }
});

答案 1 :(得分:1)

尝试:

function onLoad() {
    var fields = ["SearchReference", "SearchFirstName"];
    for(var i = 0; i < fields.length; i++) {
        eworkData.FieldByName( fields[i] ).HTMLfield.onkeydown=function(evt) {
            var keyCode = evt.keyCode;
            if( keyCode == 13 ) {
                eworkData.FieldByName('cmdSearch').HTMLfield.onfocus();
                eworkData.FieldByName('cmdSearch').HTMLfield.onclick();
            }
        };
    }
}