【问题标题】:Unable to call function of one JavaScript file from function of another JavaScript file in Safari无法从 Safari 中另一个 JavaScript 文件的函数调用一个 JavaScript 文件的函数
【发布时间】:2012-06-13 11:50:30
【问题描述】:

在我的网络应用程序中,我有一个 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 浏览器中运行它。如果有人知道解决方案,请告诉我..

【问题讨论】:

  • 1) 你已经包含了 file1 两次 2) 为什么 window.function2 而不是 function function2() ?
  • 什么时候调用function1()?
  • 我编辑了我的问题,都是不同的js文件。

标签: javascript html function safari


【解决方案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 正文:

    <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);
    }

【讨论】:

  • 都需要两个js文件。这就是为什么我把它们分开。
猜你喜欢
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多