event.keycode vs event.which [英] event.keycode vs event.which

查看:87
本文介绍了event.keycode vs event.which的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为没有专注于特定字段的按键输入键(确实是任何键),所以我犯了一个Firefox keydown 行为,不会触发 keydown 事件只会触发按键事件。

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键码,而使用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.

在这种情况下,使用 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;

在搜索解决这些问题期间,我一直被事件所困惑。键码 vs 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.

非常感谢。 >

Many thanks.

推荐答案

某些浏览器使用 keyCode 而其他浏览器使用 / code>但是使用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 vs event.which的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆