参考错误:未定义变量 [英] ReferenceError: variable is not defined
本文介绍了参考错误:未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有时会遇到这个问题,但仍然不知道是什么原因造成的.
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 is 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
:
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";
.
这篇关于参考错误:未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文