简体   繁体   English

如何在 document.ready 中定义全局函数?

[英]How to define global function inside document.ready?

I want to define a global function inside document.ready which need to be called outside document.ready .我想定义一个全局函数里面document.ready需要被称为外面document.ready I tried to define a function as我试图将一个函数定义为

var global_fn={};
$(document.ready).function(){
   global_fn.my_function=function(){
    console.log('my function');
   };
global_fn.my_function();
}
global_fn.my_function();

The function call global_fn.my_function();函数调用global_fn.my_function(); inside document.ready works well, but outside it throws error: Uncaught TypeError: global_fn.my_function is not a function .document.ready内部运行良好,但在外部抛出错误: Uncaught TypeError: global_fn.my_function is not a function What things I am missing?我缺少什么东西?

NB.注意。 The reason for defining function inside document.ready is because of third party api I am using, which works only after dom is ready and the reason for making it global is because I want to call it in another js file.document.ready里面定义函数的原因是因为我使用了第三方 api,它只有在 dom 准备好后才起作用,将其设为全局的原因是因为我想在另一个 js 文件中调用它。

The reason it doesn't work outside the document.ready function is that when it's out in the js file like that, the function gets executed before it gets created in document.ready .它在document.ready函数之外不起作用的原因是,当它像这样在 js 文件中时,该函数在它在document.ready创建之前被执行。

It will be available in your other JS files as long as they don't try to access it before document.ready .只要他们不在document.ready之前尝试访问它,它就会在您的其他 JS 文件中可用。

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

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