我正在编写此代码以检测并仅允许文本框中的字母数字和退格/ del /箭头键事件。它按预期工作除了它不会阻止%
符号,单引号'
和句点.
出现。我已在localhost,w3cschool网站,笔记本电脑键盘和外置USB键盘上的不同浏览器上进行了测试。请仔细查看代码,了解为什么允许这些密钥,以及查看是否存在正则表达式/过滤器或键盘传输charcodes的问题。
TIA
编辑 如果我使用像Prusse建议的onkeydown事件,脚本将禁止出现句号或单引号,但现在它将允许所有的shift /数字字符出现!@#$%^& *等
当我同时使用onkeydown和onkeypress事件时(现在是代码),它会将条目限制为我想要%
符号除外。我不明白为什么%
符号不会被过滤。
如果我只是将keycheck变量更改为keycheck = /%/;然后过滤%符号(是的,即使代码说允许%符号)。很奇怪。我只使用普通戴尔笔记本电脑英文键盘。
<head>
<script type="text/javascript">
function keyRestricted(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var keychar = String.fromCharCode(key);
//alert(keychar);
var keycheck = /[a-zA-Z0-9]/;
if (!(key == 8 ||
key == 27 ||
key == 46 ||
key == 37 ||
key == 39 )) { // backspace delete escape arrows
if (!keycheck.test(keychar)) {
theEvent.returnValue = false; //for IE
if (theEvent.preventDefault)
theEvent.preventDefault(); //Firefox
//alert ("key allowed");
}
}
}
</script>
</head>
<body>
Please modify the contents of the text field.
<input type="text" onKeypress="return keyRestricted(event)" value="" />
</body>
答案 0 :(得分:0)
对于箭头键,退格键和类似的东西,不会触发按键事件。你不需要检查它。
在这种情况下,您获得了代表按下的键的charcode并发生了
% charcode 37
. charcode 46
' charcode 39
在按键事件中,已经应用了移位状态(例如:charCode 97,一个字符代码65)。如果你需要对不生成字符的键产生一些特殊效果,你需要在你拥有密钥代码的那些人中监听keydown / keyup事件,它们会因键盘中的每个键而被触发,并且不会应用shift状态,当您按下“A”键时无论按下换档(或大写锁定)都无关紧要,您总是得到65.
编辑:
只需删除第一个if。
编辑:
尝试:
function keyRestricted(evt) {
var theEvent = evt || window.event;
var rv = true;
//var key = theEvent.keyCode || theEvent.which;
var key = (typeof theEvent.which === 'undefined') ? theEvent.keyCode : theEvent.which;
if (key && (key !== 8)){
var keychar = String.fromCharCode(key);
var keycheck = /[a-zA-Z0-9]/;
if (!keycheck.test(keychar) )
{
rv = theEvent.returnValue = false;//for IE
if (theEvent.preventDefault) theEvent.preventDefault();//Firefox
}
}
return rv;
}
在Firefox,Chrome和IE(9-7)上测试它似乎确实想要你想要它。 对不起,发错了代码,试试这个=)