Jquery点击回调

jquery click callback

本文关键字:回调 Jquery      更新时间:2023-09-26

我有一个由'click'处理程序触发的jquery函数:

$('#showDatesCheckbox').click(function(){
    var table = $('#planningViewTable').find('tr');
    if ($('#showDatesCheckbox').is(':checked')) {
        table.find('.textDate').stop().animate({
            "opacity": 1
        }, 1000);
        table.find('.inlineTextDate').stop().animate({
            "opacity": 1
        }, 1000);
    }
    else {
        table.find('.textDate').stop().animate({
            "opacity": 0
        }, 1000);
        table.find('.inlineTextDate').stop().animate({
            "opacity": 0
        }, 1000);
    }
});

我想有一个ajax加载指示器动画,所以我需要它来显示点击触发时,隐藏操作完成时,所以我图回调但它似乎没有工作,当我设置如下:

$('#showDatesCheckbox').click(function(){
            $('#planningView').mask('Loading...');
    var table = $('#planningViewTable').find('tr');
    if ($('#showDatesCheckbox').is(':checked')) {
        table.find('.textDate').stop().animate({
            "opacity": 1
        }, 1000);
        table.find('.inlineTextDate').stop().animate({
            "opacity": 1
        }, 1000);
    }
    else {
        table.find('.textDate').stop().animate({
            "opacity": 0
        }, 1000);
        table.find('.inlineTextDate').stop().animate({
            "opacity": 0
        }, 1000);
    }
},  
    $('#planningView').unmask();
); 

立即触发click事件,持续时间为0,因此没有任何回调。

但是你正在使用的animate,确实有一个持续时间,所以它有一个回调。你的回调函数应该在.animate:

$('#showDatesCheckbox').click(function(){
    $("#foo").animate({ opacity: 1 }, 1000, function(){
        // your callback
    });
});

但是你正在使用多个动画,所以我猜你想要你的回调函数被调用当所有这些动画完成"动画"。下面是我要做的:

$('#showDatesCheckbox').click(function(){
    var callback_count = 2; // the number of animates you do before you want to actually call your callback function
    var yourCallbackFunction = function(){
        if(--callback_count <= 0){
            // your callback
        }
    }
    $("#foo").animate({ opacity: 1 }, 1000, yourCallbackFunction);
    $("#bar").animate({ opacity: 1 }, 1000, yourCallbackFunction);
});

还有一件事你应该知道:调用.animate来改变不透明度是伟大的,但如果你只改变不透明度,有一个方法只做这一点,也有一个回调:fadeIn()fadeOut()

试试这样做:

$('#showDatesCheckbox').click(function(){
$('#ajaxgif').fadeIn();
var table = $('#planningViewTable').find('tr');
if ($('#showDatesCheckbox').is(':checked')) {
    table.find('.textDate').stop().animate({
        "opacity": 1
    }, 1000);
    table.find('.inlineTextDate').stop().animate({
        "opacity": 1
    }, 1000);
}
else {
    table.find('.textDate').stop().animate({
        "opacity": 0
    }, 1000);
    table.find('.inlineTextDate').stop().animate({
        "opacity": 0
    }, 1000);
};$('#ajaxgif').fadeOut();
});

编辑:对不起,这将不工作,因为脚本将继续,而不是等到动画完成。如果答案是正确的,您必须使用animate()

中的回调选项