【发布时间】:2015-04-05 05:23:41
【问题描述】:
构建一个简单的天气应用程序,我让它与一些草率的香草 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
【问题讨论】:
-
“我得到了它与一些草率的香草 JS 一起工作。这显然是应该用 jQuery 编写的东西” - jQuery 肯定不是“必须的”。
-
所以你说
$(".dayName:nth-of-type(" + i + "n)")不匹配任何元素,还是错误的?你能检查一下它到底匹配什么吗? -
显然,它匹配每个具有 .dayName 类的元素,而不仅仅是该类的第 n 个实例。
标签: javascript jquery each