event.keycode vs event.which

廉价感情. 提交于 2019-11-29 06:07:34

问题


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.

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.

Is there any known reason why FF using keypress in this circumstance? What is the benefit?

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;

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.


回答1:


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.




回答2:


According to this comment jQuery can be unreliable and this page says:

event.which is undefined in IE<9 on keydown and keyup.

event.keyCode is 0 in Gecko (Seamonkey, Firefox) on keypress for keys that return a character.

event.charCode is only supported on keydown and keyup by Internet Explorer (Mac).

Try it on JSFiddle



来源:https://stackoverflow.com/questions/12172646/event-keycode-vs-event-which

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!