一个基础的问题 多个$(function(){})里面的函数 为什么在下一个$(function(){})里没法执行。

先看下例子

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="jquery-1.10.2_d88366fd.js"></script>
    </head>
    <body>
        <script>
            $(function(){
                function console1(){
                    console.log('js1:console1');
                }
            })
        </script>
        <script>
            $(function(){
                console1();
            })
        </script>
    </body>
</html>

这样写 console1函数无法执行报错,说没找到console1函数。

想了半天,原来每个$(function(){})都是一个函数,函数都有自己的作用域,匿名函数相当于私有的函数,要把匿名函数改成 全局函数就可以在下面用了。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="jquery-1.10.2_d88366fd.js"></script>
    </head>
    <body>
        <script>
            var console1;
            $(function(){
                console1=function (){
                    console.log('js1:console1');
                }
            })
        </script>
        <script>
            $(function(){
                console1();
            })
        </script>
    </body>
</html>

 

posted @ 2018-07-13 11:47  盖大楼  阅读(3754)  评论(0编辑  收藏  举报