如何在循环中访问jquery getJson调用($ .getJson)中的索引变量? [英] How to access index variable in a jquery getJson call ($.getJson) during a loop?

查看:258
本文介绍了如何在循环中访问jquery getJson调用($ .getJson)中的索引变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,已针对此问题进行了简化。基本上我有一个循环,在每次迭代,调用jquery getJSON函数,调用到一个API端点,以抓取一些天气数据。问题是,我需要从循环访问索引,当getJSON请求被触发,我有一些麻烦。我需要知道请求的索引,所以我可以与数据库中的一些数据匹配。

I have the following code, which has been simplified for this question. Basically i have a loop, that, on each iteration, calls the jquery getJSON function, calling out to a API end point to grab some weather data. The problem is that i need to access the index from the loop, when the getJSON request was fired, and am having some troubles with it. I need to know what index the request was for, so i can match it with some data from a database.

代码:

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/

Here is a JSFiddle that shows the issue, and that you can work on if need be ;) - http://jsfiddle.net/5tr34k/0xshvrzp/

请求:
如何在请求的回调函数中插入或访问此索引(i)?感谢您的任何帮助。

The request: How can i inject or otherwise access this index (i) inside of the callback function for the request ? Thanks for any help.

推荐答案

添加一个范围函数(IIFE),为您的变量创建一个新的范围:

Add a scoping function (an IIFE) that creates a new scope for your variable:

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);
    }
}

这篇关于如何在循环中访问jquery getJson调用($ .getJson)中的索引变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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