Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

jquery - Javascript e.keyCode doesn't catch Backspace/Del in IE

I'm trying to catch the pressing event of Backspace and Delete keys using javascript/jQuery with this kind of code.

$("textarea[name=txt]").keypress(function(e){
    var keycode =  e.keyCode ? e.keyCode : e.which;

    if(keycode == 8){ // backspace
        // do somethiing
        alert(keycode);
    }

    if(keycode == 46){ // delete
        // do somethiing
        alert(keycode);
    } 

});

These lines of code works perfectly in Firefox (3.6.12). That means the alert is popped up when Backspace or Delete is pressed. But this is not working in Internet Explorer (8)

Can anyone suggest me a different way to catch these key press events in Internet Explorer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to support IE and you use special keys (like delete and backspace) I suggest using keydown/keyup instead.

Special keys

Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.

If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.

You can read more on cross browser issues of Detecting keystrokes (Quirksmode).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...