如何在循环期间访问 jquery getJson 调用 ($.getJson) 中的索引变量?
How to access index variable in a jquery getJson call ($.getJson) during a loop?
我有以下代码,已针对此问题进行了简化。基本上我有一个循环,在每次迭代中,调用 jquery getJSON 函数,调用 API 端点来获取一些天气数据。问题是我需要从循环中访问索引,当 getJSON 请求被触发时,我遇到了一些麻烦。我需要知道请求的索引是什么,所以我可以将它与数据库中的一些数据进行匹配。
代码:
function buildCities()
{
for (var i = 0; i < 7; i++)
{
var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response)
{
alert(i); //this will always be 7 - this is the issue. i desire it to be 0,1,2,3, etc....
});
}
}
这是一个显示问题的 JSFiddle,如果需要,您可以处理它 ;)
- http://jsfiddle.net/5tr34k/0xshvrzp/
要求:
我如何在请求的回调函数中注入或以其他方式访问此索引 (i)?感谢您的帮助。
添加一个作用域函数(一个 IIFE)来为您的变量创建一个新的作用域:
function buildCities()
{
for (var i = 0; i < 7; i++)
{
(function(index){
var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response)
{
alert(index);
});
})(i);
}
}
此外,如果您可以访问 ES6,将 i 更改为 val 而不是 var 也可以。
主要问题是您正在处理函数作用域,因此您继续重复使用相同的变量与 {} 作用域的 val 或为您创建新作用域的 TrueBlueAussie 答案。
我有以下代码,已针对此问题进行了简化。基本上我有一个循环,在每次迭代中,调用 jquery getJSON 函数,调用 API 端点来获取一些天气数据。问题是我需要从循环中访问索引,当 getJSON 请求被触发时,我遇到了一些麻烦。我需要知道请求的索引是什么,所以我可以将它与数据库中的一些数据进行匹配。
代码:
function buildCities()
{
for (var i = 0; i < 7; i++)
{
var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response)
{
alert(i); //this will always be 7 - this is the issue. i desire it to be 0,1,2,3, etc....
});
}
}
这是一个显示问题的 JSFiddle,如果需要,您可以处理它 ;) - http://jsfiddle.net/5tr34k/0xshvrzp/
要求: 我如何在请求的回调函数中注入或以其他方式访问此索引 (i)?感谢您的帮助。
添加一个作用域函数(一个 IIFE)来为您的变量创建一个新的作用域:
function buildCities()
{
for (var i = 0; i < 7; i++)
{
(function(index){
var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response)
{
alert(index);
});
})(i);
}
}
此外,如果您可以访问 ES6,将 i 更改为 val 而不是 var 也可以。
主要问题是您正在处理函数作用域,因此您继续重复使用相同的变量与 {} 作用域的 val 或为您创建新作用域的 TrueBlueAussie 答案。