在一定时间后调用一个函数Jquery?

时间:2011-10-10 08:54:06

标签: jquery function time

我正在检查Bram Jetten的js文件:

Notification.fn = Notification.prototype;

function Notification(value, type, tag) {
  this.log(value, type);
  this.element = $('<li><span class="image '+ type +'"></span>' + value + '</li>');
  if(typeof tag !== "undefined") {
    $(this.element).append('<span class="tag">' + tag + '</span>');
  }
  $("#notifications").append(this.element);
  this.show();
}

/**
 * Show notification
 */
Notification.fn.show = function() {
  $(this.element).slideDown(200);
  $(this.element).click(this.hide);
}

/**
 * Hide notification
 */
Notification.fn.hide = function() {  
  $(this).animate({opacity: .01}, 200, function() {
    $(this).slideUp(200, function() {
      $(this).remove();
    });
  });
}

...

我为我的一个按钮分配了一个点击事件,当我点击该按钮时,它会调用一个新的通知:

new Notification('Hi', 'success');

当我点击该通知时,它也会关闭。但是,如果我在一段时间后没有点击它,我希望它自己关闭。我怎样才能调用隐藏功能,或者在它出现一段时间后关闭它?

4 个答案:

答案 0 :(得分:31)

var that = this;

setTimeout(function() {   //calls click event after a certain time
   that.element.click();
}, 10000);

对我有用。

答案 1 :(得分:2)

设置超时并强制隐藏。

/**
 * Show notification
 */
Notification.fn.show = function() {
  var self = this;
  $(self.element).slideDown(200)
                 .click(self.hide);

  setTimeout(function() {
    self.hide();
    // 3000 for 3 seconds
  }, 3000)
}

答案 2 :(得分:1)

将行更改为

Notification.fn.show = function() {
    var self=this;
    $(this.element).slideDown(200);
    $(this.element).click(this.hide);
    setTimeout(function(){
        self.hide();
    },2000);
}

但是你需要一个额外的内部布尔值,这样你就不能隐藏(并且会破坏)两次通知。

Notification.fn.hide = function() {
  if (!this.isHidden){  
    var self=this;
    $(this).animate({opacity: .01}, 200, function() {
      $(this).slideUp(200, function() {
        $(this).remove();
        self.isHidden=true;
      });
    });
  }
}

答案 3 :(得分:0)

在一段时间后调用click event

setTimeout(function() {   //calls click event after a certain time
      $(".signature-container .nf-field-element").append( $('#signature-pad')); 
}, 10000);