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

冷暖自知 提交于 2019-12-11 07:52:16

问题


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.


回答1:


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");
}



回答2:


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>



回答3:


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

<head>
    <script type="text/javascript" src="path/to/a.js"></script>
</head>


来源:https://stackoverflow.com/questions/27653657/how-to-call-a-function-that-is-in-a-js-file-from-another-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!