gpt4 book ai didi

Javascript 在动态调用其他 js 文件中的另一个类时出现问题

转载 作者:行者123 更新时间:2023-11-30 21:08:19 25 4
gpt4 key购买 nike

我正在尝试创建一个 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.jsdivGenerator.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com