在另一个js文件中调用一个javascript函数

时间:2022-04-24 07:27:36

I wanted to call a function defined in a first.js file in second.js file. both files are defined in an HTML file like:

我想先调用定义在a中的函数。js文件中。js文件。两个文件都在HTML文件中定义如下:

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

I want to call fn1() defined in first.js in second.js. From my searches answers were if first.js is defined first it is possible but from my tests I haven't found any way to do that. Thanks

我想先调用fn1()定义。在second.js js。在我的搜索中,答案是if first。js首先定义了它是可能的,但是从我的测试中我没有找到任何方法来实现它。谢谢

Edit:
Here's sample codes:
second.js

编辑:这里是示例代码:second.j

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

first.js

first.js

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

6 个解决方案

#1


94  

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

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

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

一个函数不能被调用,除非它在与试图调用它的函数相同或更大的范围内。

You declare function fn1 in first.js, and then in second you can just have fn1();

首先声明函数fn1。然后第二个是fn1()

1.js :

1。js:

function fn1 (){
    alert();
}

2.js :

2。js:

fn1();

index.html :

索引。html:

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

It works fine :)

它工作好:)

#2


18  

You can make the function a global variable in first.js and have a look at closure and do not put it in document.ready put it outside

首先可以将函数设置为全局变量。并查看闭包,不要放在文档中。准备把它外

you can use ajax too

您也可以使用ajax

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

same way you can use jquery getScript

使用jquery getScript的相同方法

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

#3


15  

1st JS:

JS 1:

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

2nd JS:

JS 2:

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

Hope This Helps... Happy Coding.

希望这有助于……快乐的编码。

#4


2  

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>

#5


1  

Use cache if your server allows it to improve speed.

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

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
}

And then use it like this:

然后像这样使用它:

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

Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.

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

#6


0  

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

#1


94  

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

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

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

一个函数不能被调用,除非它在与试图调用它的函数相同或更大的范围内。

You declare function fn1 in first.js, and then in second you can just have fn1();

首先声明函数fn1。然后第二个是fn1()

1.js :

1。js:

function fn1 (){
    alert();
}

2.js :

2。js:

fn1();

index.html :

索引。html:

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

It works fine :)

它工作好:)

#2


18  

You can make the function a global variable in first.js and have a look at closure and do not put it in document.ready put it outside

首先可以将函数设置为全局变量。并查看闭包,不要放在文档中。准备把它外

you can use ajax too

您也可以使用ajax

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

same way you can use jquery getScript

使用jquery getScript的相同方法

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

#3


15  

1st JS:

JS 1:

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

2nd JS:

JS 2:

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

Hope This Helps... Happy Coding.

希望这有助于……快乐的编码。

#4


2  

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>

#5


1  

Use cache if your server allows it to improve speed.

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

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
}

And then use it like this:

然后像这样使用它:

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

Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.

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

#6


0  

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