How to call a function that is in a js file from a

2019-08-10 07:06发布

I know this question has been answered many times but the solutions in those questions aren't working for me. I have a function in lets suppose, a.js. This function is outside the document.ready function and here is its format:

function thisIsFromAnotherFile(){
    alert("This alert is from another js file");
}

I'm calling this function from the other file, b.js this way:

var openFile = function(context){
    thisIsFromAnotherFile();
}

openFile is an onclick function.

onclick = "openFile(this)"

When I run this code I'm getting an Uncaught ReferenceError: thisIsFromAnotherFile is not defined. Please help me out. Thanks.

3条回答
等我变得足够好
2楼-- · 2019-08-10 07:38

you need to load a.js before you call the function

<head>
    <script type="text/javascript" src="path/to/a.js"></script>
</head>
查看更多
来,给爷笑一个
3楼-- · 2019-08-10 07:56

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it. You declare function fn1 in File1.js, and then in File2 you can just have fn1();

 File1.js
function thisIsFromAnotherFile() {
alert("working");
}

File2.js

 function openFile() {
 thisIsFromAnotherFile();
 }

**HTML**
<html>
<head>
<script src="File1.js" type="text/javascript"></script> 
<script src="File2.js" type="text/javascript"></script> 
</head>
 <body>
 <button onclick="openFile()">Click me</button>
 </body>
 </html>
查看更多
做自己的国王
4楼-- · 2019-08-10 07:57

It seems likely there's a few things you're not telling us. The following code provides a minimal, functioning example.

file1.html

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
}
</script>
<script src="filea.js"></script>
<script src="fileb.js"></script>
<style>
</style>
</head>
<body>
    <button onclick='fromFileA();'>Fire func in filea.js</button>
</body>
</html>

filea.js

function fromFileA()
{
    fromFileB();
}

fileb.js

function fromFileB()
{
    alert("now in fileb.js");
}
查看更多
登录 后发表回答