问题描述
我想阻止用户在文本框中键入某些字符(只允许[a-z],[A-Z]和下划线).我从上一个问题中得到了答案,但是如果按箭头键(在FF 3.6中),则会出现js错误:
I'd like to block users from typing certain characters in a text box (want to only allow [a-z], [A-Z], and underscore). I took this from a previous Q, but if I press the arrow keys (in FF 3.6), I get a js error:
"window.event is undefined"
这是原始代码,在这种情况下,我可以将window.event更改为什么?:
this is the original code, what can I change window.event to in this case?:
$("#myTextBox").bind("keypress", function(event) {
var charCode = (event.which) ? event.which : window.event.keyCode;
if (charCode <= 13) {
return true;
}
else {
var keyChar = String.fromCharCode(charCode);
var re = /[a-zA-Z_]/
return re.test(keyChar);
}
});
谢谢
推荐答案
您可以执行以下操作:
$("#myTextBox").bind("keypress", function(event) {
var charCode = event.which;
if (charCode <= 13) return true;
var keyChar = String.fromCharCode(charCode);
return /[a-zA-Z_]/.test(keyChar);
});
jQuery已将event.which
标准化. .您可以在此处进行测试:)
如果没有,则解决方法将是event.keyCode
,您想引用作为参数传递给此函数的event
,而不是window
的属性.在这种情况下,如果if
条件为true,它将返回...因此不需要if
/else
,您可以像上面一样简化它.
If it didn't, the fix would just be event.keyCode
, you want to refer to the event
passed as the parameter to this function, not a property on window
. In this case, if the if
condition was true, it'd return...so there's no need for an if
/else
, you can simplify it like I have above.
这篇关于阻止某些字符在文本框中键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!