jquery 回调被多次调用 [英] jquery callbacks being called multiple times

查看:29
本文介绍了jquery 回调被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 jQuery 中使用淡入淡出/幻灯片/动画功能时,回调会为应用效果的每个元素多次调用.这当然是设计使然.我只想知道最后一个回调是什么时候调用的.

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 并显示一个 alert().

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?

推荐答案

这将在调用最后一个元素的淡出时产生警报.那不一定是最后一次淡出.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆