这是我的代码的简化:
// 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()
来请求 script1.js
文件,但仍然使用 myfunc()
那里没有定义。我该如何处理?
最佳答案
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?
myfunc
是在 document.ready
事件中定义的,并且未全局公开,因此您无法在另一个事件中使用相同的内容不在此文档就绪事件内部的函数。
您需要 全局导出此函数 或 在 document.ready 事件之外定义它。
全局导出功能
$(document).ready(function(){
.
.
function myfunc(){ ... }
window.myfunc = myfunc; //this line added here
.
.
});
或者在外部定义
$(document).ready(function(){
.
.
.
.
});
function myfunc(){ ... }
关于javascript - 如何使用另一个 .js 文件中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967763/