在 jQuery 中,您可以对各种页面和其他事件进行多次调用,如下所示:
$(document).ready(function() {
您可以一路添加多个“就绪”函数定义,而不仅限于一个。当然,这有助于保持代码定义靠近其使用位置。
我的问题是,如果在一个 document.ready
函数声明中我使用 var
声明一个局部变量,它在另一个 文档中是否可用。页面也使用了ready
函数声明?
我不确定 jQuery 在这样的情况下是如何工作的;是否以某种方式将各个函数的作用域编织在一起,或者当就绪事件被触发时,每个函数是否以独立方式运行,每个函数都不知道其他函数的变量。 (我猜是第二个。)
最佳答案
My question is, if in one of the
document.ready
function declarations I declare a local variable usingvar
, will it be available in anotherdocument.ready
function declaration that's also used by the page?
不,它们是您传递给 document.ready
的函数的局部变量。
I'm not sure how jQuery works in circumstances like these; whether it weaves the various functions' scopes together somehow or if each of those functions runs in standalone fashion when the ready event is fired, each having no idea about the others' variables. (I'd guess the second.)
你是对的。 :-) 事实上,jQuery 无法混合函数的执行上下文,这些函数是由 JavaScript 引擎管理的。
不过,您可以通过将它们全部放入容器函数中来使它们全部共享父执行上下文:
(function() {
// Shared by all functions within this block
var foo = 42;
// ...
$(document).ready(function() {
if (foo === 42) {
// ...
--foo;
}
});
// ...
$(document).ready(function() {
if (foo > 0) {
// ...
--foo;
}
});
})();
我不认为我会提倡拥有多个 ready
处理程序(甚至一个,真的),除非您正在编写一个库。但这是另一个话题了。
关于javascript - document.ready() 和其他定义函数中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13292542/