简体   繁体   English

如何使用 jQuery 从另一个文件调用 JavaScript function

[英]How to use jQuery to call a JavaScript function from another file

My question:我的问题:

I have 2 files:我有 2 个文件:

//Sub.js
function Second() {
    //do something here
}

//Main.js
function One() {
    //do something here
}
$(function() {
    Second();
});

So basically, the function Second is too long;所以基本上, function 第二个太长了; therefore, I want to move it to a Sub.js file and call it from the Main.js .因此,我想将它移动到Sub.js文件并从Main.js调用它。 The problem is this function ( function Second ) has to be executed after function One because it gets some data from the function One output.问题是这个 function ( function Second ) 必须在function One之后执行,因为它从function One output 获取一些数据。

I don't know how to do this, please help.我不知道该怎么做,请帮忙。

<script src="/lib/Sub.js"></script>

<script src="/main.js"></script>

I think you should initialize firstly Sub.js before main.js in your head code. 我想在你的脑袋代码main.js之前,你应该先初始化Sub.js。

Because whenever the page is first load js are intialize one by one. 因为每当页面第一次加载时,js都会被初始化。

If you specifically want to use jQuery, 如果您特别想使用jQuery,

$.getscript("Sub.js",function(){
   Second();
});

You can include both the files in the page and on document ready call it sequentially: 您可以将文件包括在页面中,也可以在文档准备就绪时依次调用:

  $( document ).ready(function() { var result = first(); second(result); }); 

I was getting a similar problem.我遇到了类似的问题。 My solution was this.我的解决方案是这样的。 I was defining my function inside the.ready() callback.我在 .ready() 回调中定义了我的 function。 But The problem is that the functions is not accessible outside of its scope. To make this function available in the global scope (or through any object that is available in the global scope) is necessary declare outside the.ready() callback:但问题是这些函数无法在其 scope 之外访问。要使此 function 在全局 scope 中可用(或通过在全局范围内可用的任何 object),必须在 .ready() 回调之外声明:

Wrong Way:错误的方法:

$(document).ready(function() {
    function functionName () {
        // ...
    }

    // ...
});

Right Way:正确的方法:

function functionName () {
    // ...
}

$(document).ready(function() {
    // ...
});

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

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