jQuery在一定时间后删除引导警报

我正在使用示例中的动态引导警报。 见下文。

如何添加超时function,以便在X时间后警报自动关闭?

HTML:

JQUERY:

 bootstrap_alert = function() { } bootstrap_alert.warning = function(message) { $('#alert_placeholder').append('

Info!

'+ message +'
'); } bootstrap_alert.info = function(message) { $('#alert_placeholder').append('

Info!

'+ message +'
'); }

创建一个删除第一个(因此,最旧的)警报的函数:

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

[0]确保每次超时仅删除第一个警报。

然后在显示警报时调用该函数,参数是警报关闭的时间,以毫秒为单位:

 bootstrap_alert.warning = function(message) { $('#alert_placeholder').append('

Info!

'+ message +'
'); alertTimeout(5000); }

请看这个jsFiddle

试试这个

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