本文介绍了从另一个.js文件调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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

file1.js

$(document).ready(function() {

    function menuHoverStart(element, topshift, thumbchange) {

        ... function here ...

    }

});

file2.js

$(document).ready(function() {

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

});

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

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

任何想法?

推荐答案

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

The problem is, that menuHoverStart is 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):

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

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

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

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

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

这篇关于从另一个.js文件调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:11