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


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01