码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-13 12:12:13      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:code   fun   body   为什么   head   span   query   log   jquery   

先看下例子

<!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>

 

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

标签:code   fun   body   为什么   head   span   query   log   jquery   

原文地址:https://www.cnblogs.com/gaidalou/p/9304145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!