• Callback()


    在使用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> 
  • 相关阅读:
    Mysql存储引擎
    数据库事务的四大特性以及事务的隔离级别
    万万没想到,面试中,连 ClassLoader类加载器 也能问出这么多问题
    万万没想到,JVM内存区域的面试题也可以问的这么难?
    SQL Server读取及导入Excel数据
    SQL Server加密与解密
    线程之间如何通信
    mybatis 批量更新 批量添加
    vue echarts 从后台获取数据形成饼图,柱状图,折线图
    vue 视频播放
  • 原文地址:https://www.cnblogs.com/pureEve/p/6557988.html
Copyright © 2020-2023  润新知