Jquery Chaining vs Callbacks

后端 未结 2 1356
野的像风
野的像风 2020-12-15 00:51

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

2条回答
  •  既然无缘
    2020-12-15 01:15

    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.
    

提交回复
热议问题