缩短函数以捕获CTRL键盘事件

时间:2014-04-14 18:26:50

标签: javascript jquery

仅仅在我的拙见中,代码看起来很长且重复,是否有办法缩短javascript?

也允许使用流行的框架jQuery:

    //-------------------------------------------------------------------->>
    // CTRL SHORTCUT FEATURES:
    //-------------------------------------------------------------------->>
    function KeyDownHandler(evnt) {
        var evnt = evnt || window.event;

        //CTRL-S
        if (evnt.keyCode == 83 && evnt.ctrlKey) {
            evnt.preventDefault ? evnt.preventDefault() : event.returnValue = false;

            if (document.getElementById('save').disabled == false) {
                imts_save_changes()
            }

            return false;
        }
        //CTRL-X
        else if (evnt.keyCode == 88 && evnt.ctrlKey) {
            evnt.preventDefault ? evnt.preventDefault() : event.returnValue = false;

            if (document.getElementById('delete').disabled == false) {
                imts_delete_record()
            }

            return false;
        }

        //CTRL-A
        else if (evnt.keyCode == 65 && evnt.ctrlKey) {
                evnt.preventDefault ? evnt.preventDefault() : event.returnValue = false;
                    imts_add_new()          
                return false;
            }
        }

1 个答案:

答案 0 :(得分:1)

我认为其他人可能比我做得更好,但这就是我想到的:

function KeyDownHandler(evnt) {
    var evnt = evnt || window.event;

    if (evnt.ctrlKey) {
        evnt.preventDefault ? evnt.preventDefault() : event.returnValue = false;
        switch(evnt.keyCode) {
            case 83: 
                if (document.getElementById('save').disabled == false) {
                    imts_save_changes()
                }
                break;
            case 88:
                if (document.getElementById('delete').disabled == false) {
                    imts_delete_record()
                }
                break;
            case 65:
                imts_add_new()     
                break;
        };
    }

    return false;
}