开发者

How do chained functions get executed in JQuery?

When a function is chained in JQuery, what is the order of operations?

Example 1

$(selector).fun1(val,{fun2(){ }}

Example 2

$(selecter).fun1().fun2().fun3() 开发者_开发技巧


From left to right. fun3() is run on the result (=return value) of fun2(), fun2() on that of fun1().

This kind of chaining can be done in JQuery because each chainable function returns the object/element it was called on.

So $(selector).fun1() returns the $(selector) element after execution. fun2() is called from that returned element, and so on.


In this example:

$(selector).fun1(val,{fun2(){ }}

The second parameter to function one is a callback function. This means fun1 executes THEN fun2 executes.

In this example:

$(selecter).fun1().fun2().fun3()

All functions are fired off as quickly as possible if they have a duration, like say an animation. Otherwise they execute in order fun1, fun2, fun3.

So with animations, fun1, fun2 and fun3 would be 3 simultaenous overlapping animations, but with other synchronous operations, they simply happen in order.


  1. Uses a "callback" function. You're passing fun2 as an argument to fun1, fun1 then calls fun2 when it's finished.
  2. This is a really clever feature of jQuery, most of jQuery's methods return the original object the method was called on, so you can call another method on that returned object. The sequence is the same as the sequence it's written in.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜