gpt4 book ai didi

javascript - 函数内的jquery变量范围

转载 作者:行者123 更新时间:2023-12-01 02:32:28 24 4
gpt4 key购买 nike

meclass.prototype.switch = function() {
var items = [];
$.getJSON('http://localhost/jsoner.php', function(data) {
$.each(data, function(key, val) {
items.push(val);
alert(items[0]); //this works

});
});
alert(items[0]); //this does not
}

我已经对此进行了一段时间的修改,但并没有真正理解。我在所有 jquery 函数中都遇到了这个问题,所以这是我还没有学到的基本知识 - 并且没有运气找到答案。

最佳答案

getJSON 方法是异步。将立即继续执行以下语句。当服务器响应请求时,回调函数将在一段时间后执行。

因此,任何依赖于异步请求结果的代码都需要移至回调函数内。

这实际上是发生的事情:

var items = []; //Declare `items`, empty array
//Make AJAX request
alert(items[0]); //It's still an empty array
//Wait some arbitrary amount of time...

//AJAX request complete, run the callback function
alert(items[0]); //Inside callback, items now contains elements

关于javascript - 函数内的jquery变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12881004/

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