跨浏览器捕获回车键,我的解决方案不起作用

发布于 2024-11-04 10:58:32 字数 661 浏览 5 评论 0原文

我有一个我认为是跨浏览器的解决方案来捕获我正在制作的聊天脚本中的回车键,这里是:

    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);

我从其他人那里得到了这个,所以也许它已经过时了?无论如何,正如您所看到的,表单 id 属性是 chatEnter。我也尝试过使用 document.forms[0].submit ,但这也不起作用。它在 FF 中工作得很好,但在 IE8 64 位中却没有运气(这是迄今为止我测试过的唯一两个。)我在这里做错了什么?感谢您的任何帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还如梦归 2024-11-11 10:58:32

尝试使用 >

$(document).keypress(function(e) {
    if (e.which == "13") { 
        //enter pressed 
    }       
});

当然你需要 jQuery。没有比使用经过测试且广泛使用的跨浏览器框架更好的跨浏览器解决方案了。

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.

眼趣 2024-11-11 10:58:32

你是对的,你得到的示例已经过时了,并且包含处理 Netscape 4 的代码,该代码在大约十年来已经无关紧要了。

不要仅仅为此而使用 jQuery。如果您只想捕获 Enter 键,这并不难:

document.onkeydown = function(e) {
    e = e || window.event;
    if (e.keyCode == 13) {
        document.getElementById("chatEnter").submit();
    }
};

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();
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文