jQuery:如何让回调函数只运行一次

时间:2012-03-21 12:17:09

标签: javascript jquery function callback

我想只运行一次回调函数,如果它删除了某个类的所有元素,它应该运行,但由于某种原因,回调函数运行次数被删除的元素数量,所以这不是我正在寻找的对

代码(形成一个插件)

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

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

4 个答案:

答案 0 :(得分:2)

答案 1 :(得分: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在完成的回调中引用了什么,所以我使用另一个变量确定了引用。

答案 2 :(得分: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);
        } 
    }           
}); 

答案 3 :(得分:0)

我使用了下一段代码(正如Ghommey指出我的简单错误陈述)。

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

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