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

问题描述

对于jQuery,以下两个片段的结果有什么区别。什么?我正确的回调和链中的第二个项目都是在第一个动画完成时执行的?

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

vs

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

我想使用哪种类型的情况?如果我需要做更复杂的事情或切换到不同的选择器,我只使用后者吗?



提前感谢。



回调(第二个)回调函数(第二个回调函数)版本)用于运行任何不自动排队的任意代码。



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

  //。 ()会自动排队
$(selector).animate({opacity:1})。animate({opacity:0.5});






  / .css()不会自动排队,所以你需要一个回调
$(selector).animate({opacity:1},function(){
$(this).css opacity:0.5});
});






没有回拨...

  //动画开始---- v 
$(selector).animate({opacity:1})css不透明度:0.5});
// ...但是.css()立即运行------------- ^
// ...因为它不会自动添加到队列。


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.

解决方案

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.

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

09-01 23:12