Jquery 链接与回调 [英] Jquery Chaining vs Callbacks

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

问题描述

对于 jQuery,以下两个片段的结果有何不同.任何事物?回调和链中的第二个项目都在第一个动画完成时执行,我是否正确?

For jQuery, what's the difference in the outcome of the following two snippets. Anything? Am I correct that the callback and the second item in the chain are both executed upon completion of the first animation?

$(selector).animate({ opacity: 1 }).animate({ opacity: 0.5 });

对比

$(selector).animate({ opacity: 1}, function()
{
    $(this).animate({ opacity: 0.5 });
});

在什么类型的情况下,我想使用一种而不是另一种?如果我需要做一些更复杂的事情或切换到不同的选择器,我会只使用后者吗?

In what type(s) of situation would I want to use one over the other? Would I only use the latter if I needed to do something more sophisticated or switch to a different selector?

提前致谢.

推荐答案

它们实际上是相同的,因此您可能只使用第一个.

They are effectively the same, so you'd probably just use the first.

回调(第二个版本)用于运行任何未自动排队的任意代码.

Callbacks (the second version) are for running any arbitrary code that isn't automatically queued.

这包括其他 jQuery 方法,例如 .css(),例如,如果不在回调中,它将在动画完成之前运行很久.

This includes other jQuery methods like .css() for example, which if not in the callback, will run long before the animation is complete.

// .animate() is automatically queued
$(selector).animate({ opacity: 1 }).animate({ opacity: 0.5 });

<小时>

// .css() is not automatically queued, so you'd need a callback
$(selector).animate({ opacity: 1 }, function() {
    $(this).css({ opacity: 0.5 });
});

<小时>

没有回调...


Without the callback...

 // Animation starts ----v
$(selector).animate({ opacity: 1 }).css({ opacity: 0.5 });
 // ...but .css() runs immediately-------------^
 // ...because it isn't automatically added to the queue.

这篇关于Jquery 链接与回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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