Jquery Chaining vs Callbacks

泪湿孤枕 提交于 2019-11-27 15:12:12

问题


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 });

vs

$(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?

Thanks in advance.


回答1:


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.

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.



回答2:


The only difference is timing: The callback in the second example will not be executed until the first animate completes. The chained animate in the first example will happen immediately after the first animation begins.



来源:https://stackoverflow.com/questions/9314235/jquery-chaining-vs-callbacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!