2016-10-03 123 views
0

循環內的其他所有內容都能正常工作,直到它到達.change函數。當我刪除(i + 1)並將其編寫爲minMax1時,它工作正常,所以它似乎與循環變量有關。有誰知道問題是什麼?循環參數不能在函數內部工作jQuery

在函數之外,控制檯返回4個不同的值,但在它內部返回4次。

for (var i = 0; i < 4; i++) { 
    var wC = weather[i].conditions; 
    var lowC = data.forecast.simpleforecast.forecastday[i].low.celsius; 
    var highC = data.forecast.simpleforecast.forecastday[i].high.celsius; 
    var lowF = data.forecast.simpleforecast.forecastday[i].low.fahrenheit; 
    var highF = data.forecast.simpleforecast.forecastday[i].high.fahrenheit; 
    var fDay = data.forecast.simpleforecast.forecastday[i].date.weekday_short; 

    console.log (wC); 

    switch (wC) { 
     case "Clear": case "Sunny": 
      $("#weatherIcon" + (i + 1)).addClass ("wi wi-day-sunny"); 
      break; 
     case "Mostly Sunny": case "Mostly Clear": case "Partly Sunny": case "Partly Cloudy": 
      $("#weatherIcon" + (i + 1)).addClass ("wi wi-day-cloudy"); 
      break; 
     case "Mostly Cloudy": case "Overcast": case "Scattered Clouds": 
      $("#weatherIcon" + (i + 1)).addClass ("wi wi-cloudy"); 
      break; 
    } 

    $("#todayTemp").html (todayTempC + "&deg;"); 
    $("#minMax" + (i + 1)).html (lowC + "&deg;/" + highC + "&deg;"); 

    $("input:radio[name=\"system\"]").change (function() { 

    if ($(this).val() == "cel"){ 
     $("#todayTemp").html (todayTempC + "&deg;"); 
     $("#minMax" + (i + 1)).html (lowC + "&deg;/" + highC + "&deg;"); 
    } 
    else if ($(this).val() == "far") { 
     $("#todayTemp").html (todayTempF + "&deg;"); 
     $("#minMax" + (i + 1)).html (lowF + "&deg;/" + highF + "&deg;"); 
    } 
}); 

$("#fDay" + i).html (fDay); 

}

+0

你正在var()函數中使用var i。這個值在每個循環中都會改變,所以'$(「input:radio [name = \」system \「]」)。change'定義被分配了4次不同的邏輯。預期的行爲是什麼? –

+0

它應該將4個數字從攝氏變爲華氏。 –

+0

這些數字在ID的內部稱爲minMax1,minMax2等。 –

回答

0

裏面的回調方法,值時回調被調用。這意味着將始終是4(回調將始終在循環完成所有迭代後執行)。您需要爲每次迭代創建一個單獨的上下文來訪問當前迭代中的值。

Array.forEach會自動執行此操作。

['a', 'b'].forEach(function (value, i) { 
    //First iteration: value = 'a', i = 0 
    //Second iteration: value = 'b', i = 1 
}); 

您也可以綁定你的回調方法。看到這個例子:

http://jsbin.com/xuhoduhuxi/edit?html,js,console,output

+0

乾杯:)我將如何將forEach應用到我的代碼? –

+0

這樣的事情應該工作: http://jsbin.com/voqofoyidi/10/edit?html,js,console,output – amcdrmtt

+0

這工作輝煌謝謝:)我拉從API的一切,我還能怎麼樣圍繞天氣陣列工作? –