我想在second.js文件中调用在first.js文件中定义的函数。这两个文件都定义在HTML文件中,如下所示:

<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>

我想在second.js中调用first.js中定义的fn1()。从我的搜索答案是,如果first.js是首先定义的,这是可能的,但从我的测试中,我还没有找到任何方法来做到这一点。

这是我的代码:

second.js

document.getElementById("btn").onclick = function() {
    fn1();
}

first.js

function fn1() {
    alert("external fn clicked");
}

当前回答

我也遇到过同样的问题。我已经在jquery文档中定义了函数。

$(document).ready(function() {
   function xyz()
   {
       //some code
   }
});

我在另一个文件中调用了这个函数xyz()。这不起作用:)你必须在文档准备好上面定义函数。

其他回答

window.onload = function(){
    document.getElementById("btn").onclick = function(){
        fn1();
    }
   // this should work, It calls when all js files loaded, No matter what position you have written
});

在创建函数时使用“var”,然后您可以从另一个文件访问该函数。确保两个文件都能很好地连接到您的项目,并且可以相互访问。

file_1.js

var firstLetterUppercase = function(str) {
   str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
      return letter.toUpperCase();
   });
   return str;
}

从file_2.js文件中访问这个函数/变量

firstLetterUppercase("gobinda");

输出=> Gobinda

我也遇到过同样的问题。我已经在jquery文档中定义了函数。

$(document).ready(function() {
   function xyz()
   {
       //some code
   }
});

我在另一个文件中调用了这个函数xyz()。这不起作用:)你必须在文档准备好上面定义函数。

TLDR:首先加载全局函数文件,然后加载事件处理程序

无论何时你访问JS文件或<script>块中的元素,都必须检查以确保元素存在,即jQuery的$(document).ready()或纯JS的document。addEventListener (DOMContentLoaded”内,函数(事件)…

但是,在为DOMContentLoaded添加事件侦听器的情况下,已接受的解决方案不起作用,您可以从注释中轻松观察到这一点。

首先加载全局函数文件的步骤

解决方法如下:

分离JS脚本文件的逻辑,以便每个文件只包含事件监听器或全局的独立函数。 首先加载带有全局独立函数的JS脚本文件。 加载带有事件监听器的JS脚本文件。与前面的其他文件不同,请确保将代码包装在文档中。addEventListener('DOMContentLoaded',函数(事件){…})。或document.Ready()。

first.js

function first() { alert("first"); }

Second.js

var imported = document.createElement("script");
imported.src = "other js/first.js";  //saved in "other js" folder
document.getElementsByTagName("head")[0].appendChild(imported);


function second() { alert("Second");}

index . html

 <HTML>
    <HEAD>
       <SCRIPT SRC="second.js"></SCRIPT>
    </HEAD>
    <BODY>
       <a href="javascript:second()">method in second js</a><br/>
       <a href="javascript:first()">method in firstjs ("included" by the first)</a>
    </BODY>
</HTML>