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.
相关文章