简体   繁体   中英

Unable to call function defined in a separate file

I have a function login defined in a file index.js :

function login(un, pass){
    ....
}

In my index.html , I have:

<head>
    <title>Title</title>
    <script src="index.js"></script>
</head>

<body>
    ....
    <script>
        ....
        login("user", "pass");
    </script>
    ....
</body>

But this gives me the following error in the console:

Uncaught ReferenceError: login is not defined

Both index.html and index.js are in the same folder. What am I missing here?

EDIT

One crucial detail I missed out was that I was hosting this using a Flask server. After some research, I realised that the js file has to be in a folder named static .

As a better practise, another way to achieve this in EcmaScript 6, is to simply define the function and 'export' it as a module. You can then 'import' the module from another Javascript file or within the HTML tags as seen below, ensuring the path to files are accurate:

./src/index.js:

var login = function (user, pass) { ... }

export { login };

index.html:

<script>
    import login from './src/index'
    ...
    login ("user", "pass");
    ...
</script>

Check the file permissions of "index.js" maybe it is not accessible?

Also try referring to it as

<script src="../yourFolder/index.js"></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