从另一个 .js 文件调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4335069/
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-23 11:57:22  来源:igfitidea点击:

Calling a javascript function from another .js file

javascriptjquery

提问by Tom

I have two external .js files. The first contains a function. The second calls the function.

我有两个外部 .js 文件。第一个包含一个函数。第二个调用函数。

file1.js

文件1.js

$(document).ready(function() {

    function menuHoverStart(element, topshift, thumbchange) {

        ... function here ...

    } 

});

file2.js

文件2.js

$(document).ready(function() {

    setTimeout(function() { menuHoverStart("#myDiv", "63px", "myIMG"); },2000); 

});

The trouble is that this is not running the function. I need the two separate files because file2.js is inserted dynamically depending on certain conditions. This function works if I include the setTimeout... line at the end of file1.js

问题是这并没有运行该功能。我需要两个单独的文件,因为 file2.js 是根据特定条件动态插入的。如果我在 file1.js 末尾包含 setTimeout... 行,则此功能有效

Any ideas?

有任何想法吗?

回答by jwueller

The problem is, that menuHoverStartis not accessible outside of its scope (which is defined by the .ready()callback function in file #1). You need to make this function available in the global scope (or through any object that is available in the global scope):

问题是,它menuHoverStart不能在其范围之外访问(由.ready()文件 #1 中的回调函数定义)。您需要使该函数在全局范围内可用(或通过在全局范围内可用的任何对象):

function menuHoverStart(element, topshift, thumbchange) {
    // ...
}

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

If you want menuHoverStartto stay in the .ready()callback, you need to add the function to the global object manually (using a function expression):

如果要menuHoverStart留在.ready()回调中,则需要手动将函数添加到全局对象中(使用函数表达式):

$(document).ready(function() {
    window.menuHoverStart = function (element, topshift, thumbchange) {
        // ...
    };
    // ...
});

回答by Quentin

You have declared menuHoverStartinside a function (the anonymous one you pass to the ready ready). That limits its scope to that function and you cannot call it from outside that function.

您已menuHoverStart在函数内部声明(传递给就绪就绪的匿名函数)。这将其范围限制为该函数,并且您不能从该函数外部调用它。

It doesn't doanything there, so there is no need to hold off on defining it until the ready event fires, so you could just move it outside the anonymous function.

它在那里不做任何事情,所以在 ready 事件触发之前不需要推迟定义它,所以你可以把它移到匿名函数之外。

That said, globals are worth avoiding, so you might prefer to define a namespace (to reduce the risk of name collisions) and hang the function off that.

也就是说,全局变量值得避免,因此您可能更愿意定义一个名称空间(以降低名称冲突的风险)并将函数挂起。

var MYNAMESPACE = {}; // In the global scope, not in a function
// The rest can go anywhere though
MYNAMESPACE.menuHoverStart = function (element, topshift, thumbchange) {