jQuery:重写匿名回调到命名函数
如果我这样做:
$('h1').slideUp('slow', function() { $('div:first').fadeOut(); });
h1将向上滑动,然后第一个div将淡出。
但是,如果我这样做:
function last() { $('div:first').fadeOut(); } $('h1').slideUp('slow', last());
h1会向上滑动,div会同时淡出!
如何使我的第二个示例与第一个示例相同,其中fadeOut()被称为AFTER slideUp()?
您不需要使用函数返回值(通过调用函数获得),但函数体:
$('h1').slideUp('slow', last);
你做的是和以下一样:
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
的回调函数。
希望这个例子能帮助你理解:
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