1

私のWebアプリケーションには、1つのindex.htmlファイルと2つの外部.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ブラウザで実行しようとしています。誰かが解決策を知っているなら、教えてください。

4

1 に答える 1

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"/>

(file1.jsはfile1.jsに依存しているように見えるため、前にfunction2を配置しましたが、これをどこでどのように呼び出すかによって異なります)

しかし、なぜ file2.js を function1 に含めようとするのでしょうか? 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);
    }
于 2012-06-13T11:53:21.163 に答える