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

当前回答

迟到总比不到好

(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 ()

其他回答

使用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>
// module.js
export function hello() {
  return "Hello";
}

// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";

参考来自https://hype.codes/how-include-js-file-another-js-file

在创建函数时使用“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

你可以在first.js中把这个函数设置为全局变量 看一下闭包,不要把它放在文档里。准备好了,放到外面

你也可以使用ajax

    $.ajax({
      url: "url to script",
      dataType: "script",
      success: success
    });

与使用jquery getScript的方法相同

$.getScript( "ajax/test.js" )
  .done(function( script, textStatus ) {
    console.log( textStatus );
  })
  .fail(function( jqxhr, settings, exception ) {
    $( "div.log" ).text( "Triggered ajaxError handler." );
});

您可以考虑使用es6导入导出语法。在文件1中;

export function f1() {...}

然后在文件2;

import { f1 } from "./file1.js";
f1();

请注意,这只适用于你使用<script src="./file2.js" type="module">

如果这样做,您将不需要两个脚本标记。您只需要主脚本,就可以导入所有其他内容。