简体   繁体   中英

External JavaScript file not working - ReferenceError

So, I have this really weird error. I am trying to link to an external JS file from my HTML file. Whatever I do, the functions in that external JS file can not be called.

This is my HTML code:

<html>
    <head>
        <meta charset="UTF-8">
        <script src="cookies.js"></script>
        <script type="text/javascript">
            //some other JavaScript...
            function test() {
                extTest();
            }
        </script>
    </head>
    <body>
        <button type="button" onclick="test();">Test</button>
    </body>
</html>

And this is my external JavaScript file:

function extTest() {
    alert("Hello world");
}

(I simplified both code blocks to contain only the necessary lines.)

So, whenever I click the button, the function extTest() is supposed to open a popup saying "Hello world". But extTest() is not called. Instead, I get a ReferenceError saying "extTest is not defined". The problem occurs in Firefox as well as Chrome and Edge.

Both files (HTML and JS) are in the same directory on my laptop. I tried linking to the JS file with a relative link (as shown in the code above), a relative link using . for current directory (./cookies.js), and an absolute link (/C:/...). I also tried putting the JS file in its own folder and linking to it, it didn't work.

I'd consider myself rather a beginner when it comes to JavaScript, but I already used external JS files and it worked. Do you guys have any idea where this error comes from? I mean, I could put all the code from the external file into the script in the HTML file, but I'm really curious why it's not working the other way.

Any hints are highly appreciated, thank you in advance.

You can use just like this, you don't need to make another function inside because i suppose you make the js code in cookies.js

<html>
    <head>
        <meta charset="UTF-8">
        <script src="cookies.js"></script>
    </head>
    <body>
        <button type="button" onclick="extTest();">Test</button>
    </body>
</html>

I'd say initially it looks like you are declaring your function test but not invoking it. Try putting a line below that just has: test ();

A question, if you similarly invoke your extTest function at the bottom of your external .js file, by which I mean again putting a line that says extTest(); does it work as intended? If it doesn't, then there may be another issue at hand.

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