2012-03-21 86 views
0

我想運行一次回調函數,它應該運行,如果它刪除所有具有某個類的元素,但由於某種原因,回調函數運行時間乘以元素數量這是刪除,所以這不是我正在尋找。jQuery:如何讓一個回調函數只運行一次

代碼(形成一個插件)

 $.plugin= { 
     clear: function(str){ 

      $('.msg').fadeOut(200, function(){ 
       $(this).remove(); 
       if(typeof str.remove == 'function'){ 
        str.remove.call(this); 
       }   
      }); 
     } 
    } 
+0

我們需要看到更多的代碼。除了別的以外,不知道'str'是指什麼。 – maxedison 2012-03-21 12:19:34

+0

@ maxedison是正確的。我們需要知道的其中一件事是'.remove()'方法中包含的代碼,以及它如何對給定的範圍作出反應(因爲你明確指出'.call()'在範圍刪除了元素[s])。 – JAAulde 2012-03-21 12:24:19

+0

我已經更新了代碼,這是基本的插件部分。我已經將回調放在範圍內,只有當元素被移除時它才應該運行。回叫可以包含某種用戶使用的功能。 – user759235 2012-03-21 12:29:05

回答

2

最簡單的方法是取消設置功能:

$('.msg').fadeOut(200, function(){ 
     $(this).remove(); 
     if(typeof str.remove == 'function'){ 
      str.remove.call(this); 
      str.remove = false; 
     }   
    }); 

JAAulde可能是正確的。 下面的代碼調用回調與所有的.msg元素:

var $msgs = $('.msg').fadeOut(200, function(){ 
     $(this).remove(); 
     if(typeof str.remove == 'function'){ 
      str.remove.call($msgs); 
      str.remove = false; 
     }   
    }); 

注意$('.msg')慢(特別是在IE 7及以下)和沒有標記不應當被使用。 的原因是,他們不支持document.querySelectorAll(麥克庚說)

+0

類選擇器一般?或者什麼是慢? – jgauffin 2012-03-21 12:21:26

+0

爲什麼它慢?是否因爲缺少querySelectorAll? – 2012-03-21 12:21:55

+1

http://www.artzstudio.com/2009/04/jquery-performance-rules/#use-tags-before-classes – jantimon 2012-03-21 12:22:12

0

我建議另一種方法:因爲您可能需要再次使用該功能後,我不想重寫功能,但稱這只是一次

var l = $('.msg').length; 
$('.msg').fadeOut(200, function(){ 
    $(this).remove(); 
    if((--l === 0) && typeof str.remove == 'function'){ 
     str.remove.call(this); 
    }   
}); 

,如果你要一次執行兩個功能只寫

var l = $('.msg').length; 
$('.msg').fadeOut(200, function(){ 
    if (--l === 0) { 
     $(this).remove(); 
     if(typeof str.remove == 'function'){ 
      str.remove.call(this); 
     } 
    }   
}); 
1

這應該做的任務:

var msgs = $('.msg').fadeOut(200); 
    msgs.promise().done(function(){ 
     msgs.remove(); 
     if(typeof str.remove == 'function'){ 
      str.remove.call(this); 
     }   
    }); 

請參閱http://api.jquery.com/fadeOut/#callback-functionhttp://api.jquery.com/promise/。我不確定this在完成的回調中指的是什麼,所以我確定了一個額外的變量。

+0

我不知道promise的API,所以我會看看它,看看它是什麼。 – user759235 2012-03-21 13:45:36

+0

這是解決你的問題所做的事情:-)好的,不,[Deferred](http://api.jquery.com/category/deferred-object/)是一個更好的概念,但在這裏使用很好。 – Bergi 2012-03-21 15:49:38

+0

是的,它很好地使用了promise():+1 – fcalderan 2012-03-21 17:21:28

0

我已經使用了下一段代碼(正如Ghommey指出我的簡單虛假陳述)。

$.plugin= { 
    clear: function(str){ 

     $('.msg').fadeOut(200, function(){ 
      $(this).remove(); 
      if(typeof str.remove == 'function'){ 
       str.remove.call(this); 
       str.remove = false; 
      }   
     }); 
    } 
}