最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - event.keyCode == 13 not working in Firefox - Stack Overflow

programmeradmin1浏览0评论

I have a function to send ments on enter (and not send on shift+enter):

$(msg).keypress(function (e) {
    if (event.keyCode == 13 && event.shiftKey) {
        event.stopPropagation();
    } else if (e.which == 13) {
        // ...
    }
});

It is working on Chrome but not in Firefox.

I have a function to send ments on enter (and not send on shift+enter):

$(msg).keypress(function (e) {
    if (event.keyCode == 13 && event.shiftKey) {
        event.stopPropagation();
    } else if (e.which == 13) {
        // ...
    }
});

It is working on Chrome but not in Firefox.

Share Improve this question edited Oct 27, 2015 at 17:09 sdgluck 27.4k12 gold badges81 silver badges95 bronze badges asked Oct 27, 2015 at 17:02 RGSRGS 4,2635 gold badges40 silver badges74 bronze badges 8
  • 1 What exactly is "not working"? The ment is not sent? Or it is sent even if shift is pressed? – Felix Kling Commented Oct 27, 2015 at 17:03
  • 1 jQuery normalizes keycodes using event.which but you would need e.which – charlietfl Commented Oct 27, 2015 at 17:05
  • 2 The argument you are accepting is e but you are accessing event. – sdgluck Commented Oct 27, 2015 at 17:05
  • 1 Why are you using event? – Derek 朕會功夫 Commented Oct 27, 2015 at 17:06
  • 1 And of course, in the one case you're checking shiftKey and in the other, you aren't. – T.J. Crowder Commented Oct 27, 2015 at 17:06
 |  Show 3 more ments

2 Answers 2

Reset to default 4

It's failing in Firefox because you've tried to reference the IE-specific global event variable (which Chrome also provides, as a bone thrown to IE-specific code), as sdgluck pointed out. Firefox doesn't have that, and so the code throws an error.

Use the argument your handler is passed (e in your example), and use which, which jQuery will normalize for you.

I think the correct way of doing it is to use this:

$(msg).keypress(function(e) {

    var key = e.keyCode || e.which;

    if(key == 13 && e.shiftKey) {
        e.stopPropagation();
    }
});
发布评论

评论列表(0)

  1. 暂无评论