[英]How can I use a function which is into another .js file?
Here is the simplified of my code: 这是我的代码的简化:
// 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?
.
.
});
As you can see, I've used $.getScript()
to require sccript1.js
file, but still myfunc()
is not defined there. 正如您所看到的,我使用
$.getScript()
来要求sccript1.js
文件,但仍未在那里定义myfunc()
。 How can I handle that? 我该怎么处理?
As you can see, I've used $.getScript() to require sccript1.js file, but still myfunc() is not defined there.
正如您所看到的,我使用$ .getScript()来要求sccript1.js文件,但仍未在那里定义myfunc()。 How can I handle that?
我该怎么处理?
myfunc
is defined inside a document.ready
event and is not exposed globally , hence you are not able to use the same in another function which is not inside this document ready event . myfunc
在document.ready
事件中定义,并且不会全局公开 ,因此您无法在另一个不在此文档就绪事件中的函数中使用它。
You need to either export this function globally or define it outside document.ready event . 你需要以 全局导出此函数 或 定义它的document.ready事件之外 。
Export function globally 全球出口功能
$(document).ready(function(){
.
.
function myfunc(){ ... }
window.myfunc = myfunc; //this line added here
.
.
});
Or define it outside 或者在外面定义它
$(document).ready(function(){
.
.
.
.
});
function myfunc(){ ... }
try: 尝试:
var myfunc=null;
// script1.js
$(document).ready(function(){
.
.
myfunc = function (){ ... }
.
.
});
// script2.js
$(document).ready(function(){
.
.
myfunc();
.
});
//util.js //util.js
var test = (function (){
return {
myfunc : function (){ ... }
}
})();
// script1.js // script1.js
$(document).ready(function(){
test.myfunc();
});
// script2.js // script2.js
$(document).ready(function(){
// $.getScript("./script1.js");
test.myfunc()
});
in your html you should put this order 在您的HTML中,您应该下订单
<script src="util.js"></script>
<script src="script1.js"></script>
<script src="script2.js"></script>
Try to using absolute path. 尝试使用绝对路径。 For example https://example.com/js/script1.js instead ./script1.js
例如https://example.com/js/script1.js而不是./script1.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.