简体   繁体   中英

Unable to call function of one JavaScript file from function of another JavaScript file in Safari

In my web application, I have one index.html file, two external .js files file1.js, file2.js, I want to call function of file1.js file from function of file2.js file. I tried it with many things. But I couldn't call function2 from function1. Here is my code..

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

I'm trying to run it in Safari browser. If anyone knows the solution, please tell me..

<script type = "text/javascript" src = "file1.js"/>
<script type = "text/javascript" src = "file1.js"/>

You put 2 times the same file. Change it to :

<script type = "text/javascript" src = "file2.js"/>
<script type = "text/javascript" src = "file1.js"/>

(I've put function2 before as file1.js seems to depend from file1.js but it depends on where and how you call all this)

But why do you try to include the file2.js in function1 ? Just let it in the header script elements of your html file and remove the 4 first lines of function1.

And a seems to come from nowhere.


So I suggest you do this :

index.html header

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM