3

document.ready 内で関数を宣言すると、エラーが発生します。このような

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

エラーが発生します:「ReferenceError:updateSizeOptionsが定義されていません」。
しかし、関数を document.ready の外に移動すると、すべて正常に動作します。
このような

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

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

なぜ ?

4

3 に答える 3

7

JavaScript では、他の関数内で宣言された関数はローカル参照であり、親関数のスコープ外では表示されないためです。関数をグローバルにアクセス可能にしたい場合は、プロパティupdateSizeOptionsなどのグローバル名前空間で関数への参照を割り当てる必要があります。window

window.updateSizeOptions = updateSizeOptions;
于 2012-11-19T14:29:52.660 に答える
0

updateSizeOptionsに渡された無名関数内で関数を定義したため$(document).readyupdateSizeOptionsエクスポートしない限り、その無名関数内でのみ使用できます。(すなわちwindow.updateSizeOptions = updateSizeOptions

グローバルスコープで定義された関数(または/および変数)は文字通りオブジェクトの下で定義されているwindowため、グローバルスコープで関数を定義すると、関数alert(window.updateSizeOptions)が表示されます。window.updateSizeOptions == updateSizeOptionsを返しtrueます。

ただし、ローカルスコープ内で定義すると、が表示されますundefined

于 2012-11-19T14:33:29.903 に答える
0

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.

于 2012-11-19T14:34:27.403 に答える