jQuery: Rewriting Anonymous Callback to a Named Function

独自空忆成欢 提交于 2019-12-24 13:03:51

问题


If I do this:

$('h1').slideUp('slow', function() { $('div:first').fadeOut(); });

h1 will slide up, then the first div will fade out.

However, if I do this:

function last() { $('div:first').fadeOut(); }

$('h1').slideUp('slow', last());

h1 will slide up and div will fade out at the same time!

How can I make my second example work the same as the first one, where fadeOut() is called AFTER slideUp()?


回答1:


You don't need to use the function return value (which you get by calling the function), but the function body:

$('h1').slideUp('slow', last);

What you did is the same as this:

var returned = last();             // call to last returns undefined
                                   // so returned has the value undefined
$('h1').slideUp('slow', returned); // simply sending undefined as a callback

So you were just executing the last function inline, and then passing the return value (which is undefined since it returns nothing) as a parameter to the slideUp's callback function.


Hope this example will help you understand:

function outer() {
  function inner() {};
  return inner;
}

alert(outer);    // returns the outer function body
alert(outer());  // returns the outer function's return value, which is the inner function


来源:https://stackoverflow.com/questions/28268338/jquery-rewriting-anonymous-callback-to-a-named-function

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