简体   繁体   English

在另一个.js文件中调用javascript方法

[英]call a javascript method in another .js file

what is the rule around calling functions from one js to another ? 从一个js到另一个js调用函数的规则是什么? I thought that this worked but i am not running into issue (figured it out through firefox) that a function in another js file doesn't seem to be recognized in my first js file. 我认为这有效,但我没有遇到问题(通过firefox计算出来),在我的第一个js文件中似乎没有识别出另一个js文件中的函数。

Is there some rule around ordering or some trick you have to do to get this to work? 是否有一些关于订购的规则或者你需要做些什么才能让它发挥作用?

It has to be accessible in the global scope somewhere. 它必须可以在某个地方的全球范围内访问。 For example: 例如:

// file1.js
function hello() {
    alert("Hello, world!");
}
// file2.js
$(function() {
    hello();
});

Likely, you have something like this: 可能,你有这样的事情:

// file1.js
$(function() {
    function hello() {
        alert("Hello, world!");
    }
    // ...
});
// file2.js
$(function() {
    hello();
});

hello is only in scope of the closure defined in file1.js . hello仅在file1.js定义的闭包范围内。 Therefore, to access it in file2.js , you'd have to export it to somewhere where file2.js can get at it: 因此,要在file2.js访问它,您必须将其导出到file2.js可以获取的位置:

// file1.js
$(function() {
    function hello() {
        alert("Hello, world!");
    }
    window.hello=hello;
});
// file2.js
$(function() {
    hello();
});

Also, the script where the function is defined must be loaded, parsed, and executed before the function can be called from another script. 此外,必须先加载,解析和执行定义函数的脚本,然后才能从另一个脚本调用该函数。

Are you calling the function in an event handler, or immediately when the javascript file is loaded? 你是在事件处理程序中调用函数,还是在加载javascript文件时立即调用? If it's not in an event handler, then load order is important. 如果它不在事件处理程序中,那么加载顺序很重要。 If you have circular dependencies, you may need to delay some of the initialization with a "DOM ready" or window.onLoad listener. 如果您有循环依赖关系,则可能需要使用“DOM ready”或window.onLoad侦听器来延迟某些初始化。

The browser parses the javascript files in the order they appear in the HTML. 浏览器按照它们在HTML中出现的顺序解析javascript文件。 So if a function that is excecuted in the first file relies on a function that is in the second file it won't work. 因此,如果第一个文件中的某个函数依赖于第二个文件中的函数,它将无法工作。 If you use $(function() {}); 如果你使用$(function(){}); for example with jQuery this is instructing the javascript to wait until the onload event is fired from the window object. 例如,使用jQuery,这是指示javascript等待从窗口对象触发onload事件。 This ensures all the elements on the page have been loaded prior to execution. 这可确保在执行之前加载页面上的所有元素。

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

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