简体   繁体   English

在 JavaScript 中的 onkeypress 中捕获某些 keyCode 的最佳实践

[英]Best practice for trapping certain keyCodes in onkeypress in JavaScript

I'm somewhat curious about the "best practices" when it comes to trapping the ENTER key in an HTML input tag.我对在 HTML input标签中捕获ENTER键时的“最佳实践”有些好奇。 In IE, it's easy.在 IE 中,这很容易。 window.event.keyCode will be 13 when enter is pressed and it's pretty straight forward.按下回车键时window.event.keyCode将是13并且非常简单。 In all other browsers, an arguments object is passed into the function.在所有其他浏览器中,参数对象被传递到函数中。 However, this seems to basically force you to late-bind a function handler to the object.但是,这似乎基本上迫使您将函数处理程序后期绑定到对象。 You can do:你可以做:

myInput.onkeypress = function (args) {
   window.alert(args.keyCode);
};

However, if you wanted to do:但是,如果您想做:

<input onkeypress="checkEnter()" />

Then basically checkEnter() would be called by an anonymous function (which in theory would have the argument object) which would then call checkEnter() with no parameters.然后基本上checkEnter()将被一个匿名函数调用(理论上它会有参数对象)然后调用checkEnter()没有参数。 I guess you could do something totally wacky like:我想你可以做一些完全古怪的事情,比如:

<input onkeypress="checkEnter(arguments)" />

I haven't tried this but I assume it could work.我没有试过这个,但我认为它可以工作。 It seems that this design basically says late-binding is the only reasonable approach for trapping key presses.似乎这种设计基本上是说后期绑定是捕获按键的唯一合理方法。 I'm not a fan of IE in any way, but it seems to me IE got this one right and their design is superior.我无论如何都不是 IE 的粉丝,但在我看来 IE 做对了这个,而且他们的设计更胜一筹。

Am I missing something?我错过了什么吗?

As a general rule, you shouldn't ever be specifying JavaScript functions in HTML tags anyway.作为一般规则,您无论如何都不应该在 HTML 标签中指定 JavaScript 函数。 Let JavaScript code define what JavaScript needs to do, and let the HTML be completely unaware of JavaScript's existence.让 JavaScript 代码定义 JavaScript 需要做什么,让 HTML 完全不知道 JavaScript 的存在。

In the case of event handlers, that does indeed mean binding functions within the script, rather than in HTML tag parameters.在事件处理程序的情况下,这确实意味着在脚本中绑定函数,而不是在 HTML 标记参数中。

The best practice is using what you call late-binding.最佳实践是使用您所说的后期绑定。 Also, you should use addEventListener instead of onkeypress, at least in theory.此外,您应该使用addEventListener而不是 onkeypress,至少在理论上是这样。

Another way would be to bind events using some library, like jQuery .另一种方法是使用一些库来绑定事件,比如jQuery

Check out how to do it with jQuery .看看如何使用jQuery做到这一点。

Another great feature of javascript/jQuery is that you can make it unobtrusive, so you can completely separate your scripts from your html making both more readable and the javascript be cacheable by the browser. javascript/jQuery 的另一个很棒的特性是你可以让它不显眼,所以你可以将你的脚本与你的 html 完全分开,从而提高可读性,并且 javascript 可以被浏览器缓存。

Grz, Kris.格兹,克里斯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM