jQuery函数调用

LB.*_*LB. 1 javascript jquery

我正试图在$(document).ready(..)中调用一个回调函数

如何从外部调用函数?

例如:

$(document).ready( function(foo) {
   var bar = function() { ... };
});

// How do I call bar() from here?
Run Code Online (Sandbox Code Playgroud)

Dan*_*ert 5

这取决于你想要的范围.如果您只想让bar在全局范围内,那么只需执行以下操作:

$(document).ready( function(foo) {
   var bar = function() { ... };
   window.bar = bar;
});
Run Code Online (Sandbox Code Playgroud)

请记住,在JavaScript中有范围的唯一代码块的功能,所以变量声明中if{},while{}和其他类型的代码块是全局的任何功能,它们的一部分,除非它们不声明.

如果使用变量而不声明它,则与执行以下操作相同:

// Both of these variables have global scope, assuming
// 'bar' was never declared anywhere above this
window.foo = "Hello World!";
bar = "Hello World!";
Run Code Online (Sandbox Code Playgroud)

所以上面的例子可以通过以下方式缩短:

$(document).ready( function(foo) {
   window.bar = function() { ... };
});
Run Code Online (Sandbox Code Playgroud)

  • 这与在"bar"之前省略"var"的效果相同 (2认同)