简体   繁体   中英

How can I call a javascript function from an html file

I have a .js file defined as follows:

<script>
    function sayHello() {
        alert("Hello World");
    }
</script>

And I have a .html file defined as follows:

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="css/testCSS.css">
        <title>test html</title>
    </head>
    <body>
        <script type="text/javascript" src="js/testJS.js"></script>
    </body>
</html>

How can I call the sayHello() function?

script.js

function sayHello() {
    alert("Hello World");
}

index.html

<!doctype html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <script src="script.js"></script>
        <script>
            sayHello();
        </script>
    </body>
</html>

You just need to call it!

let me explain in an example. let's say you have a button in that html that calls sayHello function.

<button type="button" onclick="sayHello ()">Say hello</button>

I think you should take a look at here .

Jus replace the link to script with content of .Js file...

Or call the function

     <script>
       sayHello()
     </script>

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