JavaScript回调函数

一种场景

js需要等待一个函数执行完后再执行另一个函数或者其他的操作。本编以最简单的例子来说明回调函数的执行过程。回调函数备注上就是以函数对象作为参数进行传递。

demo

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Solution 4-5: Sending multiple files</title>
</head>
<body>
<div class="hh">
    <div >
        Hello world
    </div>
    <img src="hh.png" onclick = "Hello()">
</div>
<script>
    window.onload = function(){
        var classArr = document.getElementsByClassName("hh");
            console.log(classArr[0].innerText);
                alert(str);

            //call();
        }

        var str = "Hello world";
        function Hello()
        {
        //这里是回调函数的核心,首先执行test方法,然后执行test666,当然这里可以使用匿名函数。换句话就是等待test执行完毕后才执行test666。
                    test("999",function   test666(){
                    alert(str);
            })
        }
        //这是test函数的实现。最后调用callback。
        function test(s,callback)
        {
                alert(callback);
                str = s;
                test2("22",function()
                {


                            callback();
                })
                callback();
        }
        function test2(num,callback)
        {
                str=num;
        }
</script>
</body>
</html> 

js基本数据类型

字符串、数字、布尔、数组、对象、Null、Undefined

猜你喜欢

转载自blog.csdn.net/helloworlddm/article/details/80203205