jquery 不应使用keydown事件的“charCode”属性,该值无意义

wmomyfyw  于 2022-12-12  发布在  jQuery
关注(0)|答案(4)|浏览(107)

什么是直接的JavaScript语法来替换jQuery的keydown事件?Lint抱怨得太多了,以至于很难阅读我的Firebug控制台。
因为我只是为自己开发一个概念验证,所以我不担心任何跨浏览器的问题--目前它只需要在Firefox中工作。

v8wbuo2f

v8wbuo2f1#

这是因为charCode在keydown事件中确实没有意义,如果需要知道charCode,请将keydown事件更改为keypress事件。

ssm49v7z

ssm49v7z2#

根据DOM级别2事件:
DOM Level 2 Event规格未提供按钮事件模块。DOM规格的较新版本中会包含专为键盘输入设备所设计的事件模块。
所以关于按键事件没有标准,目前所有的浏览器都是按照自己的想法去做,如果你使用的是JS框架,它应该在所有的浏览器中给予一个一致的值(这毕竟是框架的要点)。

3duebb1j

3duebb1j3#

First, the others explained quite well the roots of your problem.
But for the record, answering your original question, what you need is addEventListener . This is a non-obtrusive, nice and modern way to attach events in Javascript. Works in every modern browser (so not under IE9, for those IEs you need attachEvent ).
So for example, using addEventListener, you assign events like:

var elem = document.getElementById("fos");
elem.addEventListener("keydown", whateverFunction, false);

You can also use the simple way ( elem.onkeydown=whateverFunction; ), but I discourage you to do it. With addEventListener, you can assign several handlers to the same event, and you cannot accidentally overwrite another event you or a library/3rd party script assigned.

sbtkgmzw

sbtkgmzw4#

变更

$(document).keydown(function(myEvent) {

document.onkeydown=function(myEvent){

相关问题