jQuery:将匿名回调重写为命名函数 [英] jQuery: Rewriting Anonymous Callback to a Named Function
问题描述
如果我这样做:
$('h1').slideUp('slow', function() { $('div:first').fadeOut(); });
h1 会向上滑动,然后第一个 div 会淡出.
h1 will slide up, then the first div will fade out.
但是,如果我这样做:
function last() { $('div:first').fadeOut(); }
$('h1').slideUp('slow', last());
h1 会向上滑动,div 会同时淡出!
h1 will slide up and div will fade out at the same time!
如何使我的第二个示例与第一个示例一样工作,其中fadeOut() 在slideUp() 之后被调用?
How can I make my second example work the same as the first one, where fadeOut() is called AFTER slideUp()?
推荐答案
你不需要使用函数返回值(你通过调用函数得到的),而是函数体:
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
所以您只是内联执行 last
函数,然后将返回值(它是 undefined
,因为它不返回任何内容)作为参数传递给 slideUp
的回调函数.
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
这篇关于jQuery:将匿名回调重写为命名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!