ReferenceError:未定义变量 [英] ReferenceError: variable is not defined
本文介绍了ReferenceError:未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有时会遇到这个问题,但仍然不知道是什么原因造成的。
I met this issue sometimes but still don't know what causes it.
我在页面中有这个脚本:
I have this script in the page:
$(function(){
var value = "10";
});
但浏览器显示ReferenceError:value not defined。但是,如果我去浏览器控制台输入
But the browser says "ReferenceError: value is not defined". However if I go to the browser console and input either
10
或
var value = "10";
其中任何一个都可以返回10.我的脚本有什么问题?
either of them can return 10. What is the problem with my script?
编辑:只需摆脱var即可解决问题。
just get rid of "var" can solve the problem.
推荐答案
宣布在一个闭包内,这意味着它只能在那里访问。如果您想要一个全局可访问的变量,您可以删除 var
:
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"
这相当于写 window.value = 10;
。
这篇关于ReferenceError:未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文