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

当前回答

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>

其他回答

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

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

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

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

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