许多jquery函数允许回调。大多数语法如下:
$('.selector').slideUp('fast', function(){
alert('slideUp has completed');
});
如果我正在编写自己的函数,如何在调用它之前确保它已完成(即提供回调参数)
答案 0 :(得分:5)
var foo = function(bar, callback){
console.log(bar);
if(typeof callback == "function"){
callback();
}
};
foo("hello world", function(){
console.log("done!");
});
hello world
done!
或者,您可以像这样调用回调
callback.call(this, arg1, arg2);
这会将foo
函数(和可选参数)的范围传递给回调函数。
var foo = function(bar, callback){
console.log(bar);
if(typeof callback == "function"){
callback.call(this, bar);
}
};
foo("hello world", function(x){
console.log(x + " is done!");
});
hello world
hello world is done!