How to access index variable in a jquery getJson call ($.getJson) during a loop?

非 Y 不嫁゛ 提交于 2020-01-16 18:35:13

问题


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.

The code:

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

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

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


回答1:


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



回答2:


Also if you have access to ES6 changing i to val instead of var will also work.

Main issue is you are dealing with function scoping so you keep reusing the same variable vs val which is {} scoped, or TrueBlueAussie answer which creates a new scope for you.



来源:https://stackoverflow.com/questions/29035736/how-to-access-index-variable-in-a-jquery-getjson-call-getjson-during-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!