【问题标题】:jQuery remove bootstrap alert after certain amount of timejQuery在一定时间后删除引导警报
【发布时间】:2013-05-12 08:21:24
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript jquery twitter-bootstrap timeout


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

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

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

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

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

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

      请看这个jsFiddle

      【讨论】:

      • 这会同时删除所有警报。可以说警报 a 已生成,然后是 b 。关闭顺序应该是a然后b。不是 a 和 b 在一起。
      • 除了使用 ID 是他们在追加之前的一种方式,我们可以选择 '
        抛出错误 TypeError: $(...).children(...)[0].remove is not a function
      • 如果我使用 .children('.alert').first().remove();它可以工作,但顺序相反..先是 b,然后是 a。
      • 很奇怪:它仍然以我尝试使用的相反顺序关闭警报:.find('.alert:first-child').remove();
      猜你喜欢
      相关资源
      最近更新 更多
      热门标签