jquery点击回调
我有一个由’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(); });
编辑:抱歉这不起作用,因为脚本将继续,而不是等到动画完成。 Pioul的回答是正确的,你必须使用animate()
的回调选项