开发者

The 'charCode' property of a keydown event should not be used. The value is meaningless

What is the straight JavaScript syntax to replace the jQuery's keydown event? Lint is complaining so much that it's hard to rea开发者_运维知识库d my Firebug console.

Since I'm developing a proof-of-concept for me only, I'm not worried about any cross browser problems - it only has to work in Firefox at the moment.


That's because charCode is indeed meaningless in the keydown event. Change the keydown event to a keypress event if you need to know the charCode.


According to DOM level2 Events:

The DOM Level 2 Event specification does not provide a key event module. An event module designed for use with keyboard input devices will be included in a later version of the DOM specification.

So there is no standard concerning the key events. Currently all the browsers do as they see fit. If you are using a JS framework it should give a consistent value in all browsers (that would be the main point of the framework after all).


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.


Change

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

to

document.onkeydown=function(myEvent){
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜