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

标签 javascript html function object

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

相关文章:

javascript - jQuery 切换动态生成的嵌套元素

javascript - Google map API v3 上的黑 block

javascript - 我的 JavaScript 函数由于某种原因无法运行

javascript - 从对象复制 THREE.js 矩阵

javascript - 从 Bootstrap 模式形式更新数据库

javascript - 单击加载 Bootstrap 药丸内容

php - 每10秒自动调用一个php函数

function - Pyan3安装说明

javascript - 来自函数的意外值 - JS

javascript - CouchDB 中图形中的最短路径