Calling a function from one JavaScript file which requires another

前端 未结 2 1934
执笔经年
执笔经年 2021-01-17 19:55

I am trying to call a function written in one JavaScript file from another JavaScript file. I have the following code, but it doesn\'t work:

My HTML file



        
相关标签:
2条回答
  • 2021-01-17 20:37

    Try changing the order

    <script type="text/javascript" src="js2.js"></script>
    <script type="text/javascript" src="js1.js"></script>
    <script language="javascript">
       js1();
    </script>
    

    Because you call js2(); inside js1.js, so the script js2.js should be executed before.

    In your case, i think it should still work without changing orders like this because you call js2(); inside a function. When this script is executed:

    function js1()
    {
       alert("Hello from js1");
       js2();
    }
    

    Even the js2.js is not executed yet, but you do not actually call js2(); at this time.

    Just try it to see if it works.

    0 讨论(0)
  • 2021-01-17 20:39

    I'm going to assume that's your entire HTML page.

    In order to have those scripts run, you need to have those JavaScript files in the same folder as your webpage, and to actually have a proper HTML page!

    In your HTML page, you need to include the references to your js1 and js2 files in either the head or body, and include the script you've written in the HTML page itself in the body so that it'll execute when it's loaded:

    <!DOCTYPE html>
    <!-- ^ Declaring this DOCTYPE means this is a HTML5 page. -->
    <html>
        <head>
            <!-- This will load your scripts into the document. -->
            <script src="js1.js"></script>
            <script src="js2.js"></script>
            <!--
                In a HTML5 page, you don't need to include the
                'type="text/javascript"' attribute on script tags.
                They're treated as having that by default, unless you say otherwise.
            -->
        </head>
        <body>
            <!--
                You could also include your scripts here, but I'll
                just leave these commented out since they're already included.
            <script src="js1.js"></script>
            <script src="js2.js"></script>
            -->
            <script>
            js1();
            </script>
            <!--
                You don't need 'language="javascript"' on a script tag.
                Use the type attribute, or nothing in a HTML5 page.
            -->
        </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题