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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25962958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:09:16  来源:igfitidea点击:

Calling a javascript function in another js file

javascripthtml

提问by m0j1

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:

我想调用在 second.js 文件中的 first.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.jsin second.js. From my searches answers were if first.jsis defined first it is possible but from my tests I haven't found any way to do that.

我想调用中fn1()定义first.jssecond.js. 从我的搜索答案来看,如果first.js首先定义它是可能的,但从我的测试中我还没有找到任何方法来做到这一点。

Here is my code:

这是我的代码:

second.js

second.js

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

first.js

first.js

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

回答by Fernando Mendez

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 fn1in first.js, and then in second you can just have fn1();

fn1在 first.js 中声明函数,然后在第二个你可以拥有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>

回答by Gildas.Tambo

You can make the function a global variable in first.jsand have a look at closureand do not put it in document.readyput it outside

您可以将函数设置为全局变量first.js并查看闭包,不要将其document.ready放入外部

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

回答by Akshay Tyagi

1st JS:

第一个JS:

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

2nd JS:

第二个JS:

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

Hope This Helps... Happy Coding.

希望这有助于...快乐编码。

回答by tm2josep

You could consider using the es6 import export syntax. In file 1;

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

export function f1() {...}

And then in file 2;

然后在文件 2 中;

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

Please note that this only works if you're using <script src="./file2.js" type="module">

请注意,这仅在您使用时有效 <script src="./file2.js" type="module">

You will not need two script tags if you do it this way. You simply need the main script, and you can import all your other stuff there.

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

回答by Consta Gorgan

It should work like this:

它应该像这样工作:

1.js

1.js

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

2.js

2.js

function clickedTheButton() {
  fn1();
} 

index.html

索引.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>

output

输出

Output. Button + Result

输出。 按钮 + 结果

Try this CodePen snippet: link.

试试这个 CodePen 片段:链接

回答by Thielicious

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.

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

回答by Afsar

first.js

第一个.js

function first() { alert("first"); }

Second.js

第二个.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

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

回答by phpnerd

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

回答by user213979

Please note this only works if the

请注意,这仅适用于

<script>

tags are in the body and NOT in the head.

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

So

所以

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

=> unknown function fn1()

=> 未知函数 fn1()

Fails and

失败和

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

works.

作品。

回答by taoufiqaitali

declare function in global scope with window

使用窗口在全局范围内声明函数

first.js

第一个.js

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

second.js

第二个.js

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

include like this

包括这样

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