简体   繁体   中英

Bootstrap - Prevent Alert From Closing Through JavaScript Alert Event

Kindly look at my code:

$('#myPanel').on('closed.bs.alert', function () {
    //  insert code here
});

I tried return false inside, and even passed event as parameter in function(){} and performed event.preventDefault() , but it still won't stop the alert from being closed. I need to prevent the alert from being closed in case some conditions that I will put will not be satisfied.

Perhaps this will work for you:

$('#myPanel [data-dismiss]').on('click', function () {
    return false;
});

Instead of hooking into bootstrap's event we hook into the user's click of the dismiss button, and prevent bootstrap's event from triggering.

The reason the code wasn't working is that you were adding an event handler to the event that fires after the alert has already been closed and not the one before it closes. This is what you wanted:

$('#myPanel').on('close.bs.alert', function (e) {
    e.preventPropagation();
});

Using return false; would also work but I try to use the event methods whenever I can since not all browsers interpret returning false from an event handler in the same way.

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