gpt4 book ai didi

Javascript匿名函数不更新全局变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:51:01 24 4
gpt4 key购买 nike

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

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); 在你的匿名函数中测试了吗?。

要正确确定范围,只需在 LoadMeasureTypes() 之外声明它。

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

-更新

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

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

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

关于Javascript匿名函数不更新全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6153666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com