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. 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. 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 .
You need to either export this function globally or define it outside document.ready event .
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
var test = (function (){
return {
myfunc : function (){ ... }
}
})();
// script1.js
$(document).ready(function(){
test.myfunc();
});
// script2.js
$(document).ready(function(){
// $.getScript("./script1.js");
test.myfunc()
});
in your html you should put this order
<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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.