$.each, for 循环不会逐一遍历 HTML 个元素

$.each, for loop won't iterate over HTML elements one by one

构建一个简单的天气应用程序,我用一些草率的 vanilla 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

这是笔: http://codepen.io/marcussacco/pen/azQLxy

您不想使用 nth-of-type selector ("nth child of their respective parent with the same element name") here. You want the .eq() method 获取所选元素的第 n 个。

var daynames = $(".dayName"),
    conds = $(".cond"),
    his = $(".hi"),
    los = $(".lo");
$.each(forecast.forecastday, function(i){
    dayNames.eq(i).text(this.date.weekday);
    conds.eq(i).text(this.conditions);
    his.eq(i).text(this.high.fahrenheit);
    los.eq(i).text(this.low.fahrenheit);

    console.log(this, i);
});

您的选择器有误,试试这个:

$(".dayName").eq(i).text(foreshort.date.weekday);
$(".cond").eq(i).text(foreshort.conditions);
$(".hi").eq(i).text(foreshort.high.fahrenheit);
$(".lo").eq(i).text(foreshort.low.fahrenheit);

您误解了 nth-of-type 选择器。它选择 parent 中第 n 个 child 类型的元素。在您的情况下,它不是 dayNamecondtemps,而是他们的 parent、day,即第 n 个 child。所以你当前的选择器

.dayName:nth-of-type(" + i + "n)

应该变成

.day:nth-of-type(" + i + "n) .dayName

或者用简单的英语:"The dayname of/inside the nth day."

所以那个块可以变成:

  $(".day:nth-of-type(" + i + "n) .dayName").text(foreshort.date.weekday);
  $(".day:nth-of-type(" + i + "n) .cond").text(foreshort.conditions);
  $(".day:nth-of-type(" + i + "n) .hi").text(foreshort.high.fahrenheit);
  $(".day:nth-of-type(" + i + "n) .lo").text(foreshort.low.fahrenheit);

Updated codepen