javascript - document.ready() 和其他定义函数中的局部变量

标签 javascript jquery scope

在 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 using var, will it be available in another document.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/

相关文章:

javascript - 计算有多少文件附加到许多输入

JavaScript 在尝试创建私有(private)函数时与闭包混淆

java - 我应该在哪里声明我的变量?

javascript - 单击不触发 css 动画元素

javascript - 移动友好的 CSS - 如何隐藏侧边栏?

javascript - 从 Uint8Array 转换为字符串并返回

javascript - Highcharts 饼图数据损坏

javascript - Jquery,禁用浏览器快捷键

javascript - 使用 jQuery 在悬停时显示菜单子(monad)元素

c++ - 在不同作用域访问同名变量