简体   繁体   English

全局变量JavaScript(更改值)

[英]Global Variable JavaScript (Changing Value)

Is it possible to change the value of a global variable in JavaScript? 是否可以在JavaScript中更改全局变量的值?

If so, is it possible to do it in a function called by an event listener such as "onreadyStateChange"? 如果是这样,是否可以在由事件侦听器调用的函数(例如“ 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>

You can change the value of any variable in JS, local or global. 您可以更改JS中任何变量的值(本地或全局)。 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 . 即使您声明了本地,也可以将其作为window的属性来访问全局。 You can change most properties as well; 您也可以更改大多数属性。 there are very few immutable data types in JS or the DOM. JS或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. 如果未按预期设置变量,则可以使用Firefox和Firebug 调试代码并观察发生的情况。

Please use window['dom1'] = xxx; 请使用window ['dom1'] = xxx; instead of var dom1 = xxx; 而不是var dom1 = xxx;

Please try: 请试试:

<script type="text\javascript"> 
    var dom1 = 3; 

    function work() 
    { 
        ... 
        http.onreadyStateChange=handleHttpResponse; 
        ... 
    } 

    function handleHttpResponse() 
    { 
        var xd; 
        if (http.readyState == 4) 
        { 
            if (http.status == 200) 
            { 
                if (http.responseText == "granted") 
                { 
                    *window['dom1']* = 1; 
                } 
                else 
                { 
                    *window['dom1']* = 2; 
                } 
            } 
            else 
            { 
                alert("Error"); 
            } 
        } 
    } 
</script>

You would find the global value "dom1" is finally changed! 您会发现全局值“ dom1”最终被更改!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM