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

当前回答

请注意,这仅适用于

<script>

标签在身体而不是在头部。

So

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

未知函数fn1()

失败,

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

的工作原理。

其他回答

你可以在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." );
});

它应该像这样工作:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index . html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

输出

试试这个CodePen代码片段:link。

迟到总比不到好

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

如果您的服务器允许使用缓存来提高速度,请使用缓存。

var extern =(url)=> {           // load extern javascript
    let scr = $.extend({}, {
        dataType: 'script',
        cache: true,
        url: url
    });
    return $.ajax(scr);
}
function ext(file, func) {
    extern(file).done(func);    // calls a function from an extern javascript file
}

然后像这样使用它:

ext('somefile.js',()=>              
    myFunc(args)
);  

可选地,为它制作一个原型以使其更加灵活。所以你不需要每次都定义文件,如果你调用一个函数或者你想从多个文件中获取代码。

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>