JavaScript密钥代码 [英] JavaScript Key Codes
问题描述
我正在使用我没写过的JavaScript例程。它是从文本框的 onkeydown
属性调用来防止不必要的击键。
I'm working with a JavaScript routine I didn't write. It is called from a text box's onkeydown
attribute to prevent unwanted keystrokes.
第一个参数显然没有使用。第二个参数是应该允许的字符列表。
The first argument is apparently not used. The second argument is a list of characters that should be allowed.
function RestrictChars(evt, chars) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27))
// Control key
return true;
else if (((chars).indexOf(keychar) > -1))
return true;
else
return false;
}
这似乎适用于字母数字字符。但是,。
和 /
等字符会导致此函数返回 false
,即使这些字符包含在 chars
参数中也是如此。例如,如果按。
键,键
设置为190, keychar
设置为3/4字符。
This seems to work for alpha-numeric characters. However, characters such as .
and /
cause this function to return false
, even when these characters are included in the chars
parameter. For example, if the .
key is pressed, key
is set to 190, and keychar
gets set to the "3/4" character.
任何人都可以看到这是如何工作的和/或它为什么不工作?我对JavaScript的了解不足以了解它正在尝试做什么。
Can anyone see how this was meant to work and/or why it doesn't? I don't know enough about JavaScript to see what it's trying to do.
推荐答案
有两件事是错的:首先,如果您正在分析键入的字符,则需要使用 keypress
事件而不是 keydown
,因为这是唯一能告诉您输入的实际字符可靠的事件。有关此问题和一般JavaScript关键事件的更多详细信息,请参阅 http://unixpapa.com /js/key.html 。其次,引用了一个名为 e
的变量,它不会(但应该)与 evt
参数对应。
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.
这是一个重写,假设你有一个名为 textBox
的变量引用文本输入元素。
Here's a rewrite, assuming you have a variable called textBox
that refers to the text input element.
jsFiddle: http://jsfiddle.net/9DZwL/
jsFiddle: http://jsfiddle.net/9DZwL/
代码:
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;
}
};
这篇关于JavaScript密钥代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!