event.keycode vs event.which(event.keycode 与 event.which)
问题描述
我犯了 Firefox keydown 的行为,因为在没有关注特定字段的情况下按下回车键(实际上是任何键)不会触发 keydown 事件只会触发 keypress 事件.
I fell foul of a Firefox keydown behavior in that pressing the enter key (indeed any key) without having focus on a specific field will NOT trigger a keydown event it will only trigger a keypress event.
这可能会非常令人困惑,因为 keydown 和 keyup 事件使用 JavaScript 键码,而 keypress 使用 ASCII 码.幸运的是 13(输入/返回)对两者都是通用的.
This could be very confusing as the keydown and keyup event use JavaScript key codes whereas keypress uses ASCII codes. Fortunately 13 (enter/return) is common to both.
FF 在这种情况下使用 keypress 有什么已知的原因吗?有什么好处?
Is there any known reason why FF using keypress in this circumstance? What is the benefit?
一旦确定了这一点,IE8 就抛出了一个愚蠢的问题,因为它不允许 preventDefault 要求而不是 returnValue = false 来自另一个 SO 帖子的以下片段被证明非常有用:
Once this was established IE8 threw up a silly in that it does not permit preventDefault demanding instead returnValue = false the following snippet from another SO post has proved very useful:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
在寻找解决这些问题的过程中,我一直被 event.keycode 与 event.which 混淆.也就是说,我使用类似于以下的 switch 语句做错了:
During the search to resolve these issues I have been consistently confused by event.keycode vs event.which. Namely am I doing wrong using a switch statement similar to:
$("#class_Name").bind("keydown", function(event){
    // do not test input if field controls used
    switch(event.which){
       case 13:
       //enter key 
       event.preventDefault ? event.preventDefault() : event.returnValue = false;
       break;
     }
以下是否更好,如果是,为什么?
Is the following better, if so why?
$("body").keypress(function(event){
     // stop inadvertant form submission
     if (event.keycode == "13"){
       event.preventDefault ? event.preventDefault() : event.returnValue = false;
     }
});
我只是想知道,以便我知道哪个最适合申请.
I would just like to know so that I know which is best to apply.
非常感谢.
推荐答案
有些浏览器使用keyCode,有些使用which.但是对于 jQuery,这是 规范化的,所以你不必考虑这一点.你可以选择你喜欢的那个.
Some browsers use keyCode and others use which. But with jQuery this is normalized so you don't have to think about that. You can just choose the one you prefer.
这篇关于event.keycode 与 event.which的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:event.keycode 与 event.which
 
				
         
 
            
        基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				