循环中的其他所有内容都可以正常工作,直到它到达.change函数。当我删除(i + 1)并将id写为minMax1时,它工作正常,所以它似乎与循环变量有关。有谁知道问题是什么?
在函数外部,控制台返回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 + "°");
$("#minMax" + (i + 1)).html (lowC + "° / " + highC + "°");
$("input:radio[name=\"system\"]").change (function () {
if ($(this).val() == "cel"){
$("#todayTemp").html (todayTempC + "°");
$("#minMax" + (i + 1)).html (lowC + "° / " + highC + "°");
}
else if ($(this).val() == "far") {
$("#todayTemp").html (todayTempF + "°");
$("#minMax" + (i + 1)).html (lowF + "° / " + highF + "°");
}
});
$("#fDay" + i).html (fDay);
}
答案 0 :(得分:0)
在回调方法中, i 在调用回调时引用 i 的值。这意味着 i 此时将始终为4(回调将始终在循环完成所有迭代后执行)。您需要为每次迭代创建一个单独的上下文,以便在当前迭代中访问该值。
Array.forEach将自动执行此操作,例如。
['a', 'b'].forEach(function (value, i) {
//First iteration: value = 'a', i = 0
//Second iteration: value = 'b', i = 1
});
您还可以将 i 绑定到您的回调方法。见这个例子: