jQuery remove bootstrap alert after certain amount of time

微笑、不失礼 提交于 2019-12-21 12:40:23

问题


I am using dynamic bootstrap alerts from an example. See below.

How can I add a timeout function so alert closes automatically after X time ?

HTML:

<div id="alert_placeholder"></div>

JQUERY:

bootstrap_alert = function() {
    }
bootstrap_alert.warning = function(message) {
    $('#alert_placeholder').append('<div class="alert alert-block fade in"><button type="button" class="close" data-dismiss="alert">&times;</button><h4>Info!</h4>'+ message +'</div>');
}
bootstrap_alert.info = function(message) {
    $('#alert_placeholder').append('<div class="alert alert-block alert-info fade in"><button type="button" class="close" data-dismiss="alert">&times;</button><h4>Info!</h4>'+ message +'</div>');
}

回答1:


Create a function that removes the first (hence, oldest) alert:

function alertTimeout(wait){
    setTimeout(function(){
        $('#alert_placeholder').children('.alert:first-child').remove();
    }, wait);
}

[0] to ensure that only the first alert gets removed, for each timeout.

And then call the function when you show the alert, with the parameter being how long until the alert closes, in milliseconds:

bootstrap_alert.warning = function(message) {
    $('#alert_placeholder').append('<div class="alert alert-block fade in"><button type="button" class="close" data-dismiss="alert">&times;</button><h4>Info!</h4>'+ message +'</div>');
    alertTimeout(5000);
}

Please see this jsFiddle




回答2:


try this one

$(function () {

 setTimeout(function () {
            if ($(".alert").is(":visible")){
                 //you may add animate.css class for fancy fadeout
                $(".alert").fadeOut("fast");
            }
        }, 3000)

});


来源:https://stackoverflow.com/questions/16604407/jquery-remove-bootstrap-alert-after-certain-amount-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!