我犯了 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)