2017-09-25 68 views
1

我试图做一个javascript函数调用另一个.js文件是这样的:的Javascript麻烦dynammicly调用另一个类在其他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文件将执行main函数被调用:如果我改正它应该显示样式的div

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> 

,但我得到的是一个错误,说:

TypeError: divGenerator is not a constructor[Learn More] 

但是,当我将divGenerator()类移动到myPage.html它工作正常。任何想法来解决这个问题?

+0

从浏览器的控制台,您可以分享哪一行抛出这个错误? 'TypeError:Container不是构造函数[了解更多内容]' – gurvinder372

+0

@ gurvinder372它在main.js中说:10:13。声明var test = new divGenerator()的行; – user2265229

+0

哪一行,提到具体行 – gurvinder372

回答

0

在代码中有几个问题。首先,不要将id分配给与“导出”全局构造函数名称相同的脚本元素。你需要记住id属性(和name)的任何东西都会自动暴露为window对象上的全局变量。这意味着您的案例中的divGenerator将引用HTMLScriptElement,而不是构造函数。

第二个问题与计时有关,因为您正在使用async属性加载脚本。这很好,但是你需要认识到,在这种情况下,当你在build()之后调用main时,不能指望该脚本将被加载。我建议创建脚本包装成承诺:

function callScript(file){ 
    return new Promise(function(resolve) { 
     var script = document.createElement('script'); 
     script.id = 'script-' + file; // Note different id 
     script.async = true; 
     script.src = "script/" + file + ".js"; 
     script.onload = resolve 

     document.getElementById('scriptSection').appendChild(script); 
    }) 
} 

,并使用它像这样:

<script> 
    build().then(function() { 
    main(); 
    }) 
</script> 
+0

Aww ..出现新错误。它说TypeError:build(...)是未定义的[了解更多]。 – user2265229

+0

您仍然需要包含'',其中'build'被定义。 – dfsq

+0

我不删除它.. – user2265229

1

您需要将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> 
+0

你不明白这个问题。 – dfsq