如何停止警报框按进入循环?

问题描述:

当用户在文档上按Enter键时,我会显示一个警告框,其中包含 alert()

When the user presses enter on the document, I show an alert box with alert().

浏览器(Mac OS X 10.8.4上的Chrome 27)的默认行为是当您将注意力集中在警告框上时按Enter键,它将关闭它。这将触发文档上的输入,再次显示警告框。您可以看到它如何循环。

The default behaviour the browser (Chrome 27 on Mac OS X 10.8.4) has is when you press enter when focused on the alert box, it will close it. That will trigger the enter on the document, showing the alert box again. You can see how it can loop.

请注意,当我使用鼠标在警告框中单击确定时,循环不会发生。

Note that when I use my mouse to click OK in the alert box, the loop does not happen.

如何阻止此循环?

一个例子(我使用它的真正方法很多更复杂):

An example (the real way I use this is a lot more complicated):

$(document).keyup(function(e) {
    e.preventDefault();

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

    if (keyCode == 13) {
        alert('Hello world!');
    }

    return false;
});


你可以委派 keydown 事件并使用 stopPropagation()以防止事件在警告对话框中触发时冒泡到文档,如下所示: http://jsfiddle.net/KNyzc/

you can delegate the keydown event and use stopPropagation() to prevent the event from bubbling up to the document when it is triggered on the alert dialog, like so: http://jsfiddle.net/KNyzc/

$(document).on( "keydown", function(e) {
    e.stopPropagation();
    var keyCode = e.keyCode || e.which;

    if (keyCode == 13) {
        alert('Hello world!');
    }
});

(实际上,您不需要使用 stopPropagation 。只需使用keydown事件。)

( actually, you don't need to use stopPropagation at all. Just use the keydown event. )