构建一个简单的天气应用程序,我得到了一些草率的香草JS。显然应该用jQuery编写。转换它,我在页面的4天预测部分遇到了一些麻烦。在纯JS中,我只是针对ID并从JSON对象中提取值。使用jQuery,我试图使用$ .each来迭代现在的一系列类,并注入相同的值。
我总是最终在元素中获得相同的一系列值,这对我没有任何意义。当我将值记录到控制台时,它们似乎正在迭代。每天的预测显示在控制台中,并按顺序显示。它们并没有出现在它们应该使用的元素中,即使脚本似乎在迭代元素,但是出现了问题。
在笔中你可以找到我尝试过的其他一些东西,包括在循环中构建HTML元素。
$(document).ready(function(){
var url="http://api.wunderground.";
$.getJSON(url,function(response){
var current = response.current_observation;
var forecast = response.forecast.simpleforecast;
$("#city").html(current.display_location.city + ",");
$("#state").html(current.display_location.state);
$("#weather").html(current.weather);
$("#temp").html(current.feelslike_f + "\u00B0");
$("#lastUpdate").html(current.observation_time);
$.each(forecast.forecastday, function(i){
var foreshort = forecast.forecastday[i];
$(".dayName:nth-of-type(" + i + "n)").text(foreshort.date.weekday);
$(".cond:nth-of-type(" + i + "n)").text(foreshort.conditions);
$(".hi:nth-of-type(" + i + "n)").text(foreshort.high.fahrenheit);
$(".lo:nth-of-type(" + i + "n)").text(foreshort.low.fahrenheit);
console.log(foreshort.date.weekday);
console.log(foreshort.conditions);
console.log(foreshort.high.fahrenheit);
console.log(foreshort.low.fahrenheit);
console.log(i);
}); //end .each
}); //end getJSON
}); //end ready