3

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

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.

How can I prevent this looping?

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

1 回答 1

1

您可以委托keydown事件并使用它stopPropagation()来防止事件在警报对话框上触发时冒泡到文档,如下所示: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 事件即可。)

于 2013-07-26T02:51:43.347 回答