ReferenceError: variable is not defined

前端 未结 3 1230
南旧
南旧 2020-11-30 05:51

I met this issue sometimes but still don\'t know what causes it.

I have this script in the page:

$(function(){
    var value = \"10\";
});

3条回答
  •  余生分开走
    2020-11-30 06:35

    It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var:

    $(function(){
        value = "10";
    });
    value; // "10"
    

    This is equivalent to writing window.value = "10";.

提交回复
热议问题