TA的每日心情 | 开心 2021-12-13 21:45 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
|
在使用Jquery的时候,用到Callback(),回调函数的概念。而且很多。
比如:
- $.ajax({
- url:"test.json",
- type: "GET",
- data: {username:$("#username").val()},
- dataType: "json",
- beforSend:function(){
- // 禁用按钮防止重复提交
- $("#submit").attr({ disabled: "disabled" });
- },
- complete:function(msg){
- //请求完成后调用的回调函数(请求成功或失败时均调用)
- } ,
- error:function(msg){
- //请求失败时被调用的函数
- } ,
- Sucess:function(msg){
- //请求成功后调用的回调函数
- }
- });
复制代码
回调函数大家都会用,只是Jquery封装了之后,不能让大家明白回调函数的真正使用。
JS Api 里这样解释:
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
当然我们可以在JS当中来真正尝试一下回调函数的神奇。
如果你直接在函数a里调用的话,那么这个回调函数就被限制死了。但是使用函数做参数就有下面的好处:当你a(b)的时候函数b就成了回调函数,而你还可以a(c)这个时候,函数c就成了回调函数。如果你写成了function a(){...;b();}就失去了变量的灵活性。下面是代码:
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta charset="GBK" />
- <title>回调函数(callback)</title>
- <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- var f;
- function d(){
- alert("我是Jquery定义的函数d");
- }
- var e = function(){
- alert("我也是Jquery定义的函数e");
- }
-
- function a(callback) {
- alert("我是parent函数a!");
- d();
- if (typeof callback === "function"){
- //alert(callback);
- callback();
- }
- }
- function b(){
- alert("我是回调函数b");
-
- d();
- e();
- f();
- }
- function c(){
- alert("我是回调函数c");
- d();
- e();
- f();
- }
- function test1() {
- a(b);
- }
- function test2() {
- a(c);
- }
- $(function(){
- f = function(){
- alert("我是回调函数f");
- }
- });
- </script>
- </head>
- <body >
- <h1>学习js回调函数</h1>
- <button onClick=test1()>test a(b)</button>
- <button onClick=test2()>test a(c)</button>
- <p>应该能看到调用了两个回调函数</p>
- <p > </p>
- </body>
- </html>
复制代码
网上看了一个例子,进行了修改,按上面方式可以回调成功,直接复制粘贴到HTML文件中即可测试
|
|