[英]Javascript anonymous callback function
I now what's a callback fn and how it works, but I don't seem to understand how it gets called in jQuery, for example: 我现在知道什么是回调函数fn以及它如何工作,但是我似乎不明白如何在jQuery中调用它,例如:
$('#btn').click(function(){
alert('Test');
});
I know that when the click method had finished executing, then the callback fn gets called, but I just don't understand how is that anonymous callback fn called. 我知道click方法完成执行后,便会调用回调fn,但我只是不明白匿名调用fn的调用方式。
In this example: 在此示例中:
function Greeting(function(){alert('Callback fn inside Greeting');}){
alert('Inside Greeting fn');
}
I'd assume that after the alert inside Greeting had been display, THEN my callback fn will get called, but it doesn't. 我假设在显示Greeting中的警报之后,然后将调用我的回调fn,但没有。 I just see this error "uncaught syntax error: unexpected token function".
我只是看到此错误“未捕获的语法错误:意外的令牌功能”。 My question is, how do I call the anonymous callback fn that I have as a parameter in Greeting fn?
我的问题是,如何调用在Greeting fn中作为参数的匿名回调fn? Thanks in advance.
提前致谢。
You need to do 2 things separately: 您需要分别做两件事:
In your second example, you're doing both at the same time - you need to separate them. 在第二个示例中,您同时执行两项操作-您需要将它们分开。 Here's how you'd do it:
这是您的处理方式:
// Step 1: Define the function that takes an anonymous callback
function Greeting(callback) {
console.log("inside Greeting! About to call callback.");
callback(); // Actually call the callback function.
console.log("Finished calling callback");
}
// Step 2: Call that function with the anonymous callback
Greeting(function() { console.log("This is the anonymous function."); });
The output of that code is: 该代码的输出为:
inside Greeting! About to call callback.
This is the anonymous function.
Finished calling callback
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.