在document.ready中声明的函数是未定义的? [英] function declared inside document.ready is undefined?

查看:906
本文介绍了在document.ready中声明的函数是未定义的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在document.ready中声明了一个函数,我得到一个错误。
像这样

If I declare a function inside document.ready, I get an error. Like this

$(document).ready(function(){
    function updateSizeOptions()
    {
        alert("updateSizeOptions");
    }

    var jGrid = $("#list_main");
    jGrid.jqGrid({
        url:'db.php?ajaxOp=getData',
            colModel:[
                $.extend(true,
                { name:'shape_id'
                  ,index:'shape_id'
                  ,edittype:'select'
                  ,formatter:'select'
                  ,editoptions: { onclick:"javascript:updateSizeOptions();" }
                }
                ,{}
            ]
        ....
});

它会给出Error:ReferenceError:updateSizeOptions is not defined。
但是如果我把这个函数移到document.ready之外,一切正常。

像这样 p>

It will give Error : "ReferenceError: updateSizeOptions is not defined".
But If I moved the function outside document.ready, everything works fine.
Like this

function updateSizeOptions()
{
    console.debug("updateSizeOptions");
}

$(document).ready(function(){
    var jGrid = $("#list_main");
....

为什么?

推荐答案

因为在Javascript中,在其他函数中声明的函数是 local 引用,并且在其父函数的作用域之外是不可见的如果要使 updateSizeOptions code>函数全局可访问,您需要在全局命名空间中指定一个引用,例如窗口属性:

Because in Javascript, functions declared within other functions are local references, and are not visible outside the scope of their parent function. If you want to make your updateSizeOptions function globally accessible, you will need to assign a reference to it in a global namespace, say a window property:

window.updateSizeOptions = updateSizeOptions;

这篇关于在document.ready中声明的函数是未定义的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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