jQuery回调被多次调用 [英] jquery callbacks being called multiple times
问题描述
当我在jQuery中使用fade / slide / animate函数时,回调会对应用效果的每个元素调用多次。这是当然的设计。我只想知道什么时候调用最后一个回调。
When I use the fade/slide/animate functions in jQuery the callback gets called multiple times for each element the effect is applied to. This is by design of course. I just want to know when the last callback is called.
这是我想出来的 - 它淡出所有的div,并显示一个警报回调被触发。
Here is what I came up with- it fades out all the divs and displays an alert() when the last callback is fired.
$("div").fadeOut(1000, function ()
{
if ($("div").index($(this)) == $("div").length-1)
alert("this is the final callback");
});
有一个更简单的方法来检查哪个回调是最后一个回调,或者这是唯一的方法?
Is there a simpler way to check which callback is the last one or is this the only way to do it?
推荐答案
当最后一个元素的fadeOut被调用时,会产生警报。这不一定是最后一个fadeOut。
That would produce the alert when the fadeOut on the last element was called. That would not necessarily be the last fadeOut.
var numDivs = $('div').length;
$('div').fadeOut(1000, function() {
if( --numDivs > 0 ) return;
alert('this is the final fadeout to complete');
});
查看 JSFiddle
这篇关于jQuery回调被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!