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.
4条答案
按热度按时间v8wbuo2f1#
这是因为charCode在keydown事件中确实没有意义,如果需要知道charCode,请将keydown事件更改为keypress事件。
ssm49v7z2#
根据DOM级别2事件:
DOM Level 2 Event规格未提供按钮事件模块。DOM规格的较新版本中会包含专为键盘输入设备所设计的事件模块。
所以关于按键事件没有标准,目前所有的浏览器都是按照自己的想法去做,如果你使用的是JS框架,它应该在所有的浏览器中给予一个一致的值(这毕竟是框架的要点)。
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:
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.sbtkgmzw4#
变更
至