显示动态引导警报,并在5秒后隐藏/删除它

时间:2016-02-26 00:46:37

标签: jquery

我正在尝试创建一个显示消息的函数,并在5秒后将其向上滑动并将其删除:

function message(id, content, type, target) {
    $('<div class="alert alert-'+type+'" id="'+id+'">'+content+'</div>').hide().insertBefore(target).slideDown('500', function() {
        setTimeout(function(){
            $(id).slideUp(500, function(){ $(this).remove(); });
        }, 5000);
    });
}

显示消息,但不会隐藏,也不会删除。

1 个答案:

答案 0 :(得分:3)

将您的代码更改为$('#'+id).slideUp(500, function(){ $(this).remove(); });

您忘记了选择器中的'#'+

Working jsFiddle

但是,这可以做得更好(jsFiddle here

如果是我,我会把它变成一个带有选项而不是函数的插件。这将使它更灵活,恕我直言更容易使用。我就是这样做的:

&#13;
&#13;
// define the plugin
(function($) {
  $.fn.alertify = function(options) {
    // This is the easiest way to have default options.
    var $target = this;
    var settings = $.extend({
      // These are the defaults.
      type: 'danger',
      class: 'alertify',
      content: 'There was an error',
      speed: 500,
      delay: 5000,
      complete: function() { // callback function to be called after a the display time
        $target.prev().slideUp(settings.speed, function() {
          $target.prev().remove();
        });
      }
    }, options);
    var $alert = $('<div class="alert alert-' + settings.type + ' ' + settings.class + '">' + settings.content + '</div>');
    $alert.hide().insertBefore(this).slideDown(settings.speed, function() {

      setTimeout(function() {
        settings.complete();
      }, settings.delay);

    });
  };
}(jQuery));


//---------------------------------------------------------------------

// Using the plugin

// call with no options, uses defaults
$('.test:eq(0)').alertify();

// call with alt type and content
$('.test:eq(1)').alertify({
  type: 'success',
  speed:200,
  content: 'Here is a success alert'
});

// call with alt type, content, delay, and callback
$('.test:eq(2)').alertify({
  type: 'info',
  content: 'Here is one with a custom callback',
  delay:6500,
  complete: function() { // callback function to be called after a the display time
    var $target = $('.test:eq(2)')
    $target.prev().slideUp(500, function() {
      $target.prev().remove();
      $target.html('This text was added by a custom callback function on the last alert');
    });
  }
});
&#13;
.test {

  margin-top: 35px;

}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
&#13;
&#13;
&#13;