我正在尝试创建一个 javascript
函数来调用另一个 .js
文件,如下所示:
scriptCaller.js
function callScript(file){
var script = document.createElement('script');
script.id = file;
script.type = 'text/javascript';
script.async = true;
script.src = "script/"+file+".js";
document.getElementById('scriptSection').appendChild(script);
}
然后我在其他文件中创建一些类以供该脚本调用:
divGenerator.js
function divGenerator(){
var self = this;
var div = document.createElement('div');
this.tag = function(){
return div;
}
/*and some other function to style the div*/
}
然后我创建要执行的主文件:
main.js
function build(){
callScript('divGenerator');
}
function main(){
var test = new divGenerator();
/*execute some function to style the div*/
document.getElementById('htmlSection').appendChild(script);
}
所有这三个文件都将在执行主要功能的 HTML
文件中调用:
myPage.html
<html>
<head>
<title>myPage</title>
</head>
<script src="scriptCaller.js"></script>
<script src="main.js"></script>
<body>
<div id="htmlSection"></div>
<div id="scriptSection"></div>
</body>
</html>
<script>build();</script>
<script>main();</script>
如果我更正它应该显示样式化的 div,但我得到的是一个错误:
TypeError: divGenerator is not a constructor[Learn More]
但是,当我将 divGenerator()
类移动到 myPage.html
时,它工作正常。有解决这个问题的想法吗?
最佳答案
您需要将 scriptCaller.js
和 divGenerator.js
添加到您的 html 脚本元素。
<html>
<head>
<title>myPage</title>
</head>
<script src="scriptCaller.js"></script>
<script src="main.js"></script>
<script src="scriptCaller.js"></script>
<script src="divGenerator.js"></script>
<body>
<div id="htmlSection"></div>
<div id="scriptSection"></div>
</body>
</html>
<script>build();</script>
<script>main();</script>
关于Javascript 在动态调用其他 js 文件中的另一个类时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46401973/