JavaScript Key Codes

谁都会走 提交于 2019-12-06 08:30:35

Two things are wrong with that: first, if you're analysing what character has been typed, you need to use the keypress event instead of keydown because that is the only event that tells you anything reliable about the actual character typed. For (a lot) more detail about about this and JavaScript key events in general, see http://unixpapa.com/js/key.html. Second, there are references to a variable called e which doesn't (but should) correspond with the evt parameter.

Here's a rewrite, assuming you have a variable called textBox that refers to the text input element.

jsFiddle: http://jsfiddle.net/9DZwL/

Code:

function isKeypressCharValid(e, chars) {
    e = e || window.event;

    // Allow delete, tab, enter and escape keys through
    if (/^(8|9|13|27)$/.test("" + e.keyCode)) {
        return true;
    }

    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    var charTyped = String.fromCharCode(charCode);
    return chars.indexOf(charTyped) > -1;
}

textBox.onkeypress = function(evt) {
    if (!isKeypressCharValid(evt, "abc123")) {
        return false;
    }
};

I'm not a JS person, either, but... I can explain how it's supposed to work; I don't know why you're getting the values you are for the keys you mentioned, however.

keychar = String.fromCharCode(key);

This checks to see if the key is a printable character (letter, punctuation mark, etc.)

if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
    // Control key

The above checks to see if the key is null OR (||)` 0 or 8 (backspace) or 9 (tab) or 13 (0x0D, or ENTER) or 27 (0x1B or ESCAPE) - it's exactly the Boolean result you'd expect: IF <thiscondition> or <thatcondition> or <anothercondition> or ...

else if (((chars).indexOf(keychar) > -1))

This checks to see if the keychar is in the string of characters passed as the chars parameter

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