如何使用另一个 .js 文件中的函数?

How can I use a function which is into another .js file?

这是我的代码的简化版:

// script1.js
$(document).ready(function(){
    .
    .
    function myfunc(){ ... }
    .
    .
});


// script2.js
$(document).ready(function(){
    .
    .
    //doesn't work
    $.getScript("./script1.js");
    // anyway I need to call myfunc() here ... how can I access it?
    .
    .
});

如您所见,我已经使用 $.getScript() 来要求 sccript1.js 文件,但仍然没有在其中定义 myfunc()。我该如何处理?

尝试使用绝对路径。例如 https://example.com/js/script1.js 而不是 ./script1.js

尝试:

var myfunc=null;
// script1.js
$(document).ready(function(){
    .
    .
    myfunc = function (){ ... }
    .
    .
});


// script2.js
$(document).ready(function(){
    .
    .
myfunc();
.
});

//util.js

var test = (function (){
return {
myfunc : function (){ ... }
}
})();

// script1.js

$(document).ready(function(){
  test.myfunc();
});

// script2.js

$(document).ready(function(){
   // $.getScript("./script1.js");
   test.myfunc()
});

在你的html中你应该下这个订单

<script src="util.js"></script>
<script src="script1.js"></script>
<script src="script2.js"></script>

As you can see, I've used $.getScript() to require sccript1.js file, but still myfunc() is not defined there. How can I handle that?

myfuncdocument.ready 事件中定义并且 未全局公开 ,因此您无法在另一个函数中使用相同的函数不在 此文档就绪事件.

您需要 全局导出此函数 定义它在 document.ready 事件 之外。

全局导出功能

$(document).ready(function(){
    .
    .
    function myfunc(){ ... }
    window.myfunc = myfunc; //this line added here
    .
    .
});

或者在外面定义

$(document).ready(function(){
    .
    .

    .
    .
});
function myfunc(){ ... }