全局变量 JavaScript(更改值)
JavaScript 中是否可以更改全局变量的值?
如果是这样,是否可以在事件侦听器(例如“onreadyStateChange”)调用的函数中执行此操作?
它适用于正常功能。但当我调用这样的函数时不会改变:
<script.......>
var dom1 = 3;
function work()
{
...
http.onreadyStateChange=handleHttpResponse;
...
}
function handleHttpResponse()
{
var xd;
if (http.readyState == 4)
{
if (http.status == 200)
{
if (http.responseText == "granted")
{
dom1 = 1;
}
else
{
dom1 = 2;
}
}
else
{
alert("Error");
}
}
}
</script>
Is it possible to change the value of a global variable in JavaScript?
If so, is it possible to do it in a function called by an event listener such as "onreadyStateChange"?
It's working for normal functions. but doesn't change when I call a function like this:
<script.......>
var dom1 = 3;
function work()
{
...
http.onreadyStateChange=handleHttpResponse;
...
}
function handleHttpResponse()
{
var xd;
if (http.readyState == 4)
{
if (http.status == 200)
{
if (http.responseText == "granted")
{
dom1 = 1;
}
else
{
dom1 = 2;
}
}
else
{
alert("Error");
}
}
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以更改 JS 中任何变量的值,无论是本地变量还是全局变量。在函数中,确保没有声明同名的局部变量,并且可以访问全局变量。即使您确实声明了本地变量,也可以将全局变量作为
window
的属性进行访问。您也可以更改大多数属性; JS 或 DOM 中的不可变数据类型非常少。如果变量未按您的预期设置,您可以使用 Firefox 和 firebug 来 调试代码并观察发生了什么。
You can change the value of any variable in JS, local or global. In a function, make sure you don't declare a local variable with the same name and you can access the global. Even if you do declare a local, you can access the global as a property of
window
. You can change most properties as well; there are very few immutable data types in JS or the DOM.If a variable isn't being set as you expect, you can use Firefox and firebug to debug the code and observe what's happening.
请使用window['dom1'] = xxx;而不是 var dom1 = xxx;
Please use window['dom1'] = xxx; instead of var dom1 = xxx;
请尝试一下:
你会发现全局值“dom1”终于改变了!
Please try:
You would find the global value "dom1" is finally changed!