Javascript匿名函数不更新全局变量 [英] Javascript anonymous function not updating global variable

查看:30
本文介绍了Javascript匿名函数不更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某些似乎没有更新全局变量的代码中调用了 $.getJSON,我不知道为什么.JSON 数据加载正常,但由于某种原因全局 EventOptions 数组未在 for {} 循环中更新.大写的注释是指变量.有任何想法吗?谢谢

I've got a $.getJSON call in some code that appear to be not updating a global variable, and I'm at a loss to understand why. The JSON data is being loaded OK, but for some reason the global EventOptions array is not being updated in the for {} loop. The capitalised comments refer to the variable. Any ideas? Thanks

function LoadMeasurementTypes() {
    // Clear out EventOptions
    EventOptions = ["..."];
    // Push a couple on to EventOptions - THESE ADD OK
    EventOptions.push("Temperature");
    EventOptions.push("Pulse rate");
    // Call json to get measurementTypes off the table    
    $.getJSON('./get-measurement-types.php', function (measurementTypeData) {
        // Process each json element ([0].BP, [1].ph (Urine) etc.
        for (var i = 0; i < measurementTypeData.length; ++i) {
            // e is a storage variable to contain the current element
            var e = measurementTypeData[i];
            // Add the new measurement type
            alert(e.measure_type); // OK works - we can see the measure_type
            EventOptions.push(e.measure_type); // THESE ARE NOT BEING ADDED 
        }
    } // end anonymous function
    ) // end get json call
    EventOptions.push("Last one"); // THIS ONE IS BEING ADDED
}

推荐答案

您的 EventOptions[] 不是全局可见的.我的猜测是它仍然应该在本地对您的 $.getJSON 调用可见;但是因为它现在被限制在 jquery 的范围内,所以它显然被掩盖了(你是否在你的匿名函数中 alert(EventOptions); 进行测试?.

Your EventOptions[] is not globally visible. My guess would of been that it should still be visible locally to your $.getJSON call; but because it is now scoped to jquery, its clearly obscured (did you alert(EventOptions); inside your anon function to test?.

为了正确的作用域,只需在 LoadMeasureTypes() 之外声明它.

To properly scope, just declare it outside of LoadMeasureTypes().

var EventOptions = ["..."];
function LoadMeasureTypes(){...

-更新

如果这不起作用 - 您总是可以将匿名函数拉出 $.getJSON() 并为其分配一个变量名:

if this does not work - you could always pull the anonymous function outside of the $.getJSON() and assign it a variable name:

var retreiveTypes = function(){...};

$.getJSON("..path/php", retreiveTypes);

这篇关于Javascript匿名函数不更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆