JQuery Callback and Functions

本文详细介绍了回调函数的概念,特别强调了回调函数的独特性质及其在传递参数时的正确用法。通过实例展示了如何避免常见错误,并确保回调函数按预期执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

 

The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes.

 

Another important thing to know is how to properly pass the callback.

 

 

Callback without arguments

 

For a callback with no arguments you pass it like this:

 

 $.get('myhtmlpage.html', myCallBack);

 

Note that the second parameter here is simply the function name (butnot as a string and without parentheses).

 

Functions in Javascript are 'First class citizens' and so can be passed around like variable references and executed at a later time.

 

 

Callback with arguments

 

"What do you do if you have arguments that you want to pass?", you might ask yourself.

 

Wrong

The Wrong Way (will not work!)

 

 $.get('myhtmlpage.html', myCallBack(param1, param2));


This will not work because it calls

 

myCallBack(param1, param2)

 

and then passes the return value as the second parameter to $.get()

 

Right

The problem with the above example is that myCallBack(param1, param2) is evaluated before being passed as a function.

 

Javascript and by extension jQuery expects a function pointer in cases like these. I.E. setTimeout function.

 

In the below usage, an anonymous function is created (just a block of statements) and is registered as the callback function.

 

Note the use of 'function(){'. The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope.

 

$.get('myhtmlpage.html', function(){
  myCallBack(param1, param2);
});

 

param1 and param2 are evaluated as a callback when the '$.get' is done getting the page.

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值