简体   繁体   English

在另一个js文件中调用一个JavaScript function

[英]Calling a JavaScript function in another js file

I wanted to call a function defined in a first.js file in second.js file.我想在 second.js 文件中调用在first.js文件中定义的function Both files are defined in an HTML file like:这两个文件都在 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 .我想在first.js中调用 first.js 中定义的second.js fn1() 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.根据我的搜索答案,如果首先定义first.js是可能的,但根据我的测试,我还没有找到任何方法来做到这一点。

Here is my code:这是我的代码:

second.js

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

first.js

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

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();你在 first.js 中声明函数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>

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.希望这有助于...快乐编码。

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您可以在first.js将该函数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." );
});

You could consider using the es6 import export syntax.您可以考虑使用 es6 导入导出语法。 In file 1;在文件 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.您只需要主脚本,然后就可以在那里导入所有其他内容。

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

输出。按钮 + 结果

Try this CodePen snippet: link .试试这个 CodePen 片段:链接

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.作品。

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>

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.这样你就不必每次都定义文件,如果你调用一个函数或者你想从多个文件中获取代码。

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

use "var" while creating a function, then you can access that from another file.在创建函数时使用“var”,然后您可以从另一个文件访问它。 make sure both files are well connected to your project and can access each other.确保这两个文件都很好地连接到您的项目并且可以相互访问。

file_1.js文件_1.js

var firstLetterUppercase = function(str) {
   str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
      return letter.toUpperCase();
   });
   return str;
}

accessing this function/variable from file_2.js file从 file_2.js 文件访问此函数/变量

firstLetterUppercase("gobinda");

output => Gobinda输出 => 戈宾达

hope this will help somebody, happy coding !!!希望这会帮助某人,快乐编码!!!

This is actually coming very late, but I thought I should share,这实际上来得很晚,但我想我应该分享,

in index.html在 index.html 中

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

in 1.js在 1.js 中

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

in 2.js在 2.js 中

fn1()

My idea is let two JavaScript call function through DOM.我的想法是让两个 JavaScript 通过 DOM 调用函数。

The way to do it is simple ... We just need to define hidden js_ipc html tag.方法很简单……我们只需要定义隐藏的js_ipc html标签。 After the callee register click from the hidden js_ipc tag, then The caller can dispatch the click event to trigger callee.在被调用者从隐藏的 js_ipc 标签注册点击后,调用者可以调度点击事件来触发被调用者。 And the argument is save in the event that you want to pass.如果您想通过,则参数将保存。

When we need to use above way ?什么时候需要使用上面的方式?

Sometime, the two javascript code is very complicated to integrate and so many async code there.有时,这两个 javascript 代码集成起来非常复杂,并且有很多异步代码。 And different code use different framework but you still need to have a simple way to integrate them together.不同的代码使用不同的框架,但您仍然需要有一种简单的方法将它们集成在一起。

So, in that case, it is not easy to do it.因此,在这种情况下,要做到这一点并不容易。

In my project's implementation, I meet this case and it is very complicated to integrate.在我的项目实现中,遇到了这种情况,集成起来非常复杂。 And finally I found out that we can let two javascript call each other through DOM.最后我发现我们可以让两个javascript通过DOM互相调用。

I demonstrate this way in this git code.我在这个 git 代码中演示了这种方式。 you can get it through this way.你可以通过这种方式得到它。 (Or read it from https://github.com/milochen0418/javascript-ipc-demo ) (或从https://github.com/milochen0418/javascript-ipc-demo阅读)

git clone https://github.com/milochen0418/javascript-ipc-demo
cd javascript-ipc-demo
git checkout 5f75d44530b4145ca2b06105c6aac28b764f066e

Anywhere, Here, I try to explain by the following simple case.任何地方,在这里,我尝试通过以下简单案例进行解释。 I hope that this way can help you to integrate two different javascript code easier than before there is no any JavaScript library to support communication between two javascript file that made by different team.我希望这种方式可以帮助您比以前更容易地集成两个不同的 javascript 代码,因为没有任何 JavaScript 库来支持不同团队制作的两个 javascript 文件之间的通信。

<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
    <div id="js_ipc" style="display:none;"></div>
    <div id="test_btn" class="btn">
        <a><p>click to test</p></a>
    </div>    
</body>
<script src="js/callee.js"></script>
<script src="js/caller.js"></script>
</html>

And the code css/style.css和代码 css/style.css

.btn {
    background-color:grey;
    cursor:pointer;
    display:inline-block;
}

js/caller.js js/caller.js

function caller_add_of_ipc(num1, num2) {
    var e = new Event("click");
    e.arguments = arguments;
    document.getElementById("js_ipc").dispatchEvent(e);
}
document.getElementById("test_btn").addEventListener('click', function(e) {
    console.log("click to invoke caller of IPC");
    caller_add_of_ipc(33, 22);      
});

js/callee.js js/callee.js

document.getElementById("js_ipc").addEventListener('click', (e)=>{
    callee_add_of_ipc(e.arguments);
});    
function callee_add_of_ipc(arguments) {
    let num1 = arguments[0];
    let num2 = arguments[1];
    console.log("This is callee of IPC -- inner-communication process");
    console.log( "num1 + num2 = " + (num1 + num2));
}

I wanted to call a function defined in a first.js file in second.js file.我想调用一个在second.js文件中的first.js文件中定义的函数。 both files are defined in an HTML file like:这两个文件都在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 .我想打电话给fn1()中定义first.jssecond.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.根据我的搜索答案,如果first.js定义了first.js是可能的,但是根据我的测试,我还没有找到实现此目的的任何方法。

Here is my code:这是我的代码:

second.js

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

first.js

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

better late than never迟到总比不到好

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

index html <script src="helper.js"></script> <script src="test.js"></script> index html <script src="helper.js"></script> <script src="test.js"></script>

in test.js file helper.fetchApi()在 test.js 文件helper.fetchApi()

I have had same problem.我有同样的问题。 I have had defined functions inside jquery document ready function.我已经在 jquery文档就绪函数中定义了函数。

$(document).ready(function() {
   function xyz()
   {
       //some code
   }
});

And this function xyz() I have called in another file.我在另一个文件中调用了这个函数xyz() This doesn't working :) You have to defined function above document ready .这不起作用:) 您必须在文档 ready之上定义函数。

// module.js
export function hello() {
  return "Hello";
}

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

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

TLDR: Load Global Function Files first, Then Load Event Handlers TLDR:首先加载全局 Function 文件,然后加载事件处理程序

Whenever you are accessing an element within a JS file or <script> block, it is essential to check to make sure that element exists, ie, jQuery's $(document).ready() or plain JS's document.addEventListener('DOMContentLoaded', function(event)... .每当您访问 JS 文件或<script>块中的元素时,必须检查以确保该元素存在,即 jQuery 的$(document).ready()或普通 JS 的document.addEventListener('DOMContentLoaded', function(event)...

However, the accepted solution does NOT work in the event that you add an event listener for the DOMContentLoaded, which you can easily observe from the comments.但是,如果您为 DOMContentLoaded 添加事件侦听器,则公认的解决方案不起作用,您可以从评论中轻松观察到这一点。

Procedure for Loading Global Function Files First先加载全局Function文件的步骤

The solution is as follows:解决方法如下:

  • Separate the logic of your JS script files so that each file only contains event listeners or global, independent functions.分离 JS 脚本文件的逻辑,使每个文件仅包含事件侦听器或全局独立函数。
  • Load the JS script files with the global, independent functions first.首先加载具有全局独立函数的 JS 脚本文件。
  • Load the JS script files with event listeners second.其次加载带有事件侦听器的 JS 脚本文件。 Unlike the other previous files, make sure to wrap your code in document.addEventListener('DOMContentLoaded', function(event) {...}) .与之前的其他文件不同,请确保将您的代码包装在document.addEventListener('DOMContentLoaded', function(event) {...})中。 or document.Ready() .document.Ready()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM