Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从外部js文件调用函数/嵌套函数_Javascript_Jquery_Html - Fatal编程技术网

Javascript 从外部js文件调用函数/嵌套函数

Javascript 从外部js文件调用函数/嵌套函数,javascript,jquery,html,Javascript,Jquery,Html,我在从外部js文件运行某些函数时遇到一些问题 html包括: <script src="js/file.js"></script> <script> $("#center-button").click(function() { explodePage("center"); }); </script> var explodePage = function(button) { //code here

我在从外部js文件运行某些函数时遇到一些问题

html包括:

<script src="js/file.js"></script> 

<script>
    $("#center-button").click(function() {
        explodePage("center"); 
    }); 
</script>
var explodePage = function(button) {
   //code here
   aboutPage();
}

var aboutPage = function() {
    //code here
}

explodePage函数运行正常,但一旦它调用嵌套的aboutPage函数,它就会开始向我抛出这些未捕获的类型错误。如果我不使用外部js文件,只是将所有内容都放到html中,它就可以正常工作。这是非常新的,所以可能缺少一些明显的范围或东西。有解决方案吗?

声明函数的定义如下:

function explodePage(button) {
   //code here
   aboutPage();
}

function aboutPage() {
    //code here
}
说明:

function explodePage(button) {
   //code here
   aboutPage();
}

function aboutPage() {
    //code here
}
当您使用
var
关键字来声明函数时,JS的执行就像变量初始化时一样,您不能在声明之前引用或使用变量。与名称函数定义不同,JS解释器在执行之前首先选择封闭函数,并在代码执行之前对其进行初始化。这被称为-抽象语法树,后跟JS解释器

还要记住:

function explodePage(button) {
   //code here
   aboutPage();
}

function aboutPage() {
    //code here
}

还可以在函数中绑定Jquery代码,以确保Jquery和DOM元素可用于绑定。

使用变量污染全局窗口对象不是一个好主意,因为可能会发生冲突。这是一个很好的解决方案

(function(){
   //You can declare your functions in here, and invoke them below
   $( document ).ready(function() {
      //Check that the DOM is ready, in order to manipulate it an add events
      $("#center-button").click(function() {
         explodePage("center"); 
      }); 
   });
})($); //Notice that we are injecting a dependency, in this case jQuery