简体   繁体   中英

Calling a function from one JavaScript file which requires another

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

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

js1.js

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

js2.js

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

What can I do?

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.

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>

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