[英]jQuery: Rewriting Anonymous Callback to a Named Function
如果我這樣做:
$('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
返回任何內容而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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.