开发者

Capture the enter key cross-browser, my solution isn't working

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=keyDo开发者_如何学运维wn;
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.


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.


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();
    }
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜