JavaScript: Avoiding hardcoded keycodes [duplicate]

独自空忆成欢 提交于 2019-12-22 09:11:59

问题


Possible Duplicate:
JavaScript event.keyCode constants

This is my code:

$button.on('keyup', function (event) {
    // Detect an Enter keypress
    if(event.keyCode === 13) {
        doStuff();
    }
});

As you can see, the keycode 13 is hardcoded. Is there a (cross-browser) way to fish out that number in a more semantically meaningful way?


回答1:


If you work with jQueryUI, you may use $.ui.keyCode constants:

keyCode: {
    BACKSPACE: 8,
    COMMA: 188,
    DELETE: 46,
    DOWN: 40,
    END: 35,
    ENTER: 13,
    ESCAPE: 27,
    HOME: 36,
    LEFT: 37,
    NUMPAD_ADD: 107,
    NUMPAD_DECIMAL: 110,
    NUMPAD_DIVIDE: 111,
    NUMPAD_ENTER: 108,
    NUMPAD_MULTIPLY: 106,
    NUMPAD_SUBTRACT: 109,
    PAGE_DOWN: 34,
    PAGE_UP: 33,
    PERIOD: 190,
    RIGHT: 39,
    SPACE: 32,
    TAB: 9,
    UP: 38
}

So in order to check for Enter pressed use:

if (event.keyCode === $.ui.keyCode.ENTER) { ... }



回答2:


To repeat Alex K.'s answer (I used):

"\r".charCodeAt(0)


来源:https://stackoverflow.com/questions/14276957/javascript-avoiding-hardcoded-keycodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!