问题
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