简体   繁体   中英

How to stop alert box press enter loop?

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

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!');
    }
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM