jQuery文档就绪和功能范围 [英] jQuery Document Ready and Function Scope

查看:112
本文介绍了jQuery文档就绪和功能范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供一些辅助函数,这些函数允许基于jQuery的复杂UI的各个组件隐藏或显示加载 div (在从页面的各个部分启动Ajax调用时使用).

I want to provide helper functions that allow various components of a complex jQuery-based UI to hide or show a loading div (used when an Ajax call is initiated from various portions of the page).

为此,我最初编写了这样的代码:

To that end, I initially wrote code like this:

<script type="text/javascript">
$(function ()
{
    var loadingControl = $("#loading");

    function showLoading() {
        loadingControl.show();
    }
}
</script>

但是,我很快意识到 showLoading 仅在特定的文档准备就绪范围内.

However, I quickly realized that showLoading is only in scope within that particular document ready.

遵循

https://stackoverflow.com/a/1055799/141172

我在全局范围内这样声明了 showLoading :

I declared showLoading in global scope like this:

<script type="text/javascript">
var showLoading;
$(function ()
{
    var loadingControl = $("#loading");

    function showLoading() {
        loadingControl.show();
    }
}
</script>

但是,我仍然发现 showLoading 在随后执行的 document ready 块中不可用.错误是

However, I still find that showLoading is not available in document ready blocks that execute later. The error is

"showLoading"属性的值为null或未定义,不是Function对象

The value of the property 'showLoading' is null or undefined, not a Function object

此行为可以在这里看到:

This behavior can be seen here:

http://jsfiddle.net/NfXFT/4/

jsFiddle还证明了 showLoading 实现的 document ready 运行在调用它的 document ready 块之前.

The jsFiddle also proves that the showLoading implementation's document ready runs before the document ready block that calls it.

出了什么问题,如何使该助手方法可用?

What is going wrong, and how can I make this helper method available?

我在 document ready 块中定义它,因为它依赖于可用的"#loading".是否有更好的方法来实现提供助手功能来隐藏/显示加载屏幕的相同目标?我想将其保留在辅助函数中,因为以后可能会更改实现.

I define it within a document ready block because it relies on '#loading' being available. Is there a better approach to accomplishing the same goal of providing a helper function to hide/show the loading screen? I want to keep this in a helper function because the implementation may change later.

推荐答案

发布后,我意识到自己做错了.

Right after posting, I realized what I had done wrong.

function showLoading() {
    loadingControl.show();
}

应该是

showLoading = function() {
    loadingControl.show();
}   

这篇关于jQuery文档就绪和功能范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆