2015-04-04 113 views
0

構建一個簡單的天氣應用程序,我得到它與一些草率的香草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

+1

*「我知道了一些馬虎香草JS工作,是很清楚的東西應該在jQuery的編寫。」 * - jQuery的肯定不是'必須'。 – GolezTrol 2015-04-04 21:08:09

+0

所以你說'$(「。dayName:n-type-type(」+ i +「n)」)'不匹配任何元素,或者錯誤的元素?你能檢查它匹配的是什麼嗎? – GolezTrol 2015-04-04 21:11:01

+0

顯然,它將每個元素與.dayName類相匹配,而不僅僅是該類的第n個實例。 – Marcus 2015-04-04 21:15:40

回答

0

你不想使用nth-of-type selector(「其母公司的第n個孩子與相同的元素名稱」)在這裏。您希望.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); 
}); 
+0

這是足夠的信息。謝謝! – Marcus 2015-04-04 21:19:04

0

有你的選擇錯誤,試試這個:

$(".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); 
0

你誤會了nth-of-type選擇。它選擇父類中第n個子類型的元素。在你的情況下,它不是dayName,cond en temps,但他們的母公司,day這是第n個孩子。所以,你現在選擇

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

應該成爲

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

或者用簡單的英語道: 「DAYNAME的/第n天裏面。」

所以該塊可以成爲:

$(".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