JavaScript Keycode 46是DELfunction键还是(。)句号?

我使用jquery在JavaScript中编写一些逻辑,我必须根据REGEX模式检查输入内容:

"^[a-zA-Z0-9_]*$" //Alpha-numeric and _ 

逻辑差不多完成了,我只是在过滤function键DEL时遇到了一些问题,我的逻辑是这样的:

 var FunctionsKey = new Array(8, 9, 13, 16, 35, 36, 37, 39, 46); function keypressValidation(key) { if (config.regexExp != null) { if ($.inArray(key, FunctionsKey) != -1) { return true; } else { var keyChar = String.fromCharCode(key); return RegexCheck(keyChar); } } return true; } 

如果KeyCode是数组中的其中一个,我让它通过,如果不是我得到char并将它与REGEX进行比较。 问题是:在一些浏览器中DEL和’。’ (期间标志)具有相同的密码46。

那么有一个更好的逻辑来过滤function键或者我必须为这种情况写一个条件,可能从数组中删除46并尝试将其转换为char,如果是(。)让它转到正则表达式函数,如果没有让它通过? 另一个问题是在某些浏览器中是否有更多共享密钥代码?

编辑:我建议的解决方案不会工作,因为用户按下哪个键(DEL或句点)无关紧要我至少在OPERA和FF =(。

110是十进制密钥代码,46是DEL密钥。

为了一些乐趣:把它放进去看看你打了什么! 编辑:增加了一个重点活动

  /* handle special key press */ $(document).ready(function() { function checkAKey(e) { var shouldBubble = true; switch (e.keyCode) { // user pressed the Tab case 9: { alert("Tab hit, no bubble"); shouldBubble = false; break; }; // user pressed the Enter case 13: { alert("Enter"); break; }; // user pressed the ESC case 27: { alert("Escape"); break; }; }; /* this propogates the jQuery event if true */ return shouldBubble; }; $("*").keydown(function(e) { return checkAKey(e); }); }); 

要么

 $(document).ready(function() { /* handle special key press */ function checkFieldKey(e, me) { var shouldBubble = true; switch (e.keyCode) { // user pressed the Enter case 13: { $(me).blur(); $("#somewhereElse").focus(); shouldBubble = false; break; }; }; /* this propogates the jQuery event if true */ return shouldBubble; }; /* user pressed special keys while in Selector */ $("#myField").keydown(function(e) { return checkFieldKey(e, $(this)); }); }); 

键盘上的十进制或点键代码为190 ..小数位数为110。

干杯..!!

@Mark Schultheiss的回答非常好,我还要补充一点:当你需要在输入元素外面的键盘上按下DEL按钮时(即当文本字段失去焦点时)你必须拦截它。 这可以这样做:

 $("#selector-for-a-textbox, body").keydown(function(event){ if(event.keyCode==46){ // do something here } }); 

区别在于:按下“按DELETE”键和“。” key返回键码46。

所以在keyup或key down上编写代码,然后“DELETE”键运行良好。

查看http://javascript.info/tutorial/keyboard-events

错误的代码

  window.addEventListener("keypress", dealWithKeyboard, false); 

正确代码:

 window.addEventListener("keydown", dealWithKeyboard, false); 

最终代码

  window.addEventListener("keydown", dealWithKeyboard, false); function dealWithKeyboard(e) { // CHECK KEYPRESS EVENT if(e.keyCode ==46){ delete_object();} } 

它对我有用。