在我的Web应用程序中,我有一个index.html文件,两个外部.js文件file1.js,file2.js,我想从file2.js文件的函数调用file1.js文件的函数。我尝试过很多东西。但是我无法从function1调用function2。这是我的代码..
的index.html
<head>
<script type = "text/javascript" src = "file1.js"/>
<script type = "text/javascript" src = "file2.js"/>
</head>
<body>
<input type = "button" name = "clickButton" onClick = "javascript:function1()"/>
</body>
file1.js
function function1()
{
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.scr = "file2.js";
document.head.appendChild(newScript);
function2(a);
}
file2.js
window.function2 = function(a)
{
alert("a value : "+a);
alert("Function2");
}
我正在尝试在Safari浏览器中运行它。如果有人知道解决方案,请告诉我..
答案 0 :(得分:1)
<script type = "text/javascript" src = "file1.js"/>
<script type = "text/javascript" src = "file1.js"/>
你把同一个文件放2次。将其更改为:
<script type = "text/javascript" src = "file2.js"/>
<script type = "text/javascript" src = "file1.js"/>
(我之前把function2放在file1.js似乎依赖于file1.js,但它取决于你调用所有这些的地点和方式)
但为什么要尝试在function1中包含file2.js?只需将它放在html文件的标题脚本元素中,然后删除function1的第4行。
a
似乎无处可去。
所以我建议你这样做:
index.html标题
<script type = "text/javascript" src = "file2.js"/>
<script type = "text/javascript" src = "file1.js"/>
index.html body:
<script>function1();</script>
file1.js:
function function1() {
var a = "hu ?"; // what you want
function2(a);
}
file2.js:
function function2(a) {
alert("a value : "+a);
alert("function2:"+ function2);
}