我想在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()。这不起作用:)你必须在文档准备好上面定义函数。

其他回答

JS 1:

function fn(){
   alert("Hello! Uncle Namaste...Chalo Kaaam ki Baat p Aate h...");
}

JS 2:

$.getscript("url or name of 1st Js File",function(){
fn();
});

迟到总比不到好

(function (window) {const helper = { fetchApi: function () { return "oke"}
   if (typeof define === 'function' && define.amd) {
    define(function () { return helper; });
   }
   else if (typeof module === 'object' && module.exports) {
    module.exports = helper;
  }
  else {
    window.helper = helper;
  }
}(window))

指数的html < script src = " helper.js " > < /脚本> < script src = " . js " > < /脚本>

在test.js文件中 helper.fetchApi ()

函数不能被调用,除非它是在同一个文件中定义的,或者是在尝试调用它之前加载的。

除非函数与试图调用它的函数在相同或更大的作用域中,否则不能调用它。

你可以在first.js中声明fn1函数,然后在second中你可以只声明fn1();

1. js:

function fn1 () {
    alert();
}

2. js:

fn1();

index . html:

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

使用window在全局作用域声明函数

first.js

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

second.js

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

像这样

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

这其实很晚了,但我想我应该分享一下,

在index . html

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

在1. js

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

在2. js

fn1()