function declared inside document.ready is undefin

2019-05-16 11:26发布

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();" }
                }
                ,{}
            ]
        ....
});

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");
....

WHY ?

3条回答
Evening l夕情丶
2楼-- · 2019-05-16 11:57

Scope. When you put something inside $(document).ready, the code will only be excecuted when this event is triggered and the things like variables and functions declared inside the event do not exist outside of the event unless set globally.

When you do javascript:updateSizeOptions(); it will look for a function in the global scope that in this case does not exist, therefor undefined.

查看更多
Summer. ? 凉城
3楼-- · 2019-05-16 12:00

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;
查看更多
Explosion°爆炸
4楼-- · 2019-05-16 12:08

Because you defined the function updateSizeOptions inside the anonymous function passed to $(document).ready, updateSizeOptions will only be available inside that anonymous function unless you export it. (i.e. window.updateSizeOptions = updateSizeOptions)

Functions (or/and variables) defined in the global scope is literally defined under the window object, so if you define the function in the global scope and you do alert(window.updateSizeOptions) you will see it shows a function. window.updateSizeOptions == updateSizeOptions will return true.

However if you define it inside a local scope, you will see undefined.

查看更多
登录 后发表回答