问题
I have what I thought was a cross-browser solution to capturing the enter key in a chat script I'm making, here it is:
nn=(document.layers)?true:false;
ie=(document.all)?true:false;
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
if(key=="13") document.getElementById('chatEnter').submit();
}
}
document.onkeydown=keyDown;
if(nn) document.captureEvents(Event.KEYDOWN);
I got this from someone else so perhaps it's outdated? Anyway, the form id attribute is chatEnter as you can see. I've also tried using document.forms[0].submit and that didn't work either. It works just fine in FF but no luck in IE8 64 bit (those are the only two I've tested on thus far.) What am I doing wrong here? Thanks for any help.
回答1:
try using >
$(document).keypress(function(e) {
if (e.which == "13") {
//enter pressed
}
});
ofcourse you would require jQuery for it. There can't be a better cross-browser solution than to use a tested and widely used cross browser framework.
回答2:
You're correct, the example you got is massively outdated and contains code to deal with Netscape 4, which has been irrelevant for about a decade.
Don't use jQuery just for this. It's not hard, if it's just the Enter key you want to capture:
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById("chatEnter").submit();
}
};
来源:https://stackoverflow.com/questions/5845254/capture-the-enter-key-cross-browser-my-solution-isnt-working