2016-10-04 55 views
0

基本上,当前天气通过天气API显示在我们的页面上。如何获取通过API动态生成的div内的值?

我想要做的是捕捉数据(比如说29摄氏度)并使用javascript为它创建条件。就像,如果是25-29摄氏度,会出现一个阳光明媚的图标(否则,应显示另一个图标)。

但是,当我尝试捕获数据时,控制台显示“空字符串”,尽管数据在页面上可见。我如何解决这个问题,以便捕获动态数据?

<div class="weather"> 
[DYNAMICALLY WEATHER IS DISPLAYED HERE] 
</div>  

$(document).ready(function() { 
     $.simpleWeather({ 
     location: 'Singapore, SG', 
     woeid: '', 
     unit: 'c', 
     success: function(weather) { 
      html = '<p class="widget-weather-info-temp"> '+weather.temp+'<sup class="widget-weather-deg">&deg;</sup><sup class="widget-weather-unit-temp">'+weather.units.temp+'</sup></p>'; 

      $("#weather").html(html); 
     }, 
     error: function(error) { 
      $("#weather").html('<p>'+error+'</p>'); 
     } 
     }); 
    }); 


    var $widgetInfoTemp = $(".widget-weather-info-temp").text(); 
    console.log($widgetInfoTemp); 

回答

1

不要在HTML成功后的功能您所有的逻辑追加

success: function(weather) { 
      html = '<p class="widget-weather-info-temp"> '+weather.temp+'<sup class="widget-weather-deg">&deg;</sup><sup class="widget-weather-unit-temp">'+weather.units.temp+'</sup></p>'; 

      $("#weather").html(html); 

    var $widgetInfoTemp = $(".widget-weather-info-temp").text(); 
    console.log($widgetInfoTemp); 
     }, 
1

给API的调用是异步的,所以你需要把你的console.log()success处理函数。这样做时,您不需要从DOM请求元素,因为您已经可以访问返回的数据。试试这个:

$(document).ready(function() { 
    $.simpleWeather({ 
     location: 'Singapore, SG', 
     woeid: '', 
     unit: 'c', 
     success: function(weather) { 
      html = '<p class="widget-weather-info-temp">' + weather.temp + '<sup class="widget-weather-deg">&deg;</sup><sup class="widget-weather-unit-temp">' + weather.units.temp + '</sup></p>'; 
      $("#weather").html(html); 

      // work with the weather data here... 
      console.log(weather); 
      console.log(weather.temp); 
      console.log(weather.units.temp); 
     }, 
     error: function(error) { 
      $("#weather").html('<p>' + error + '</p>'); 
     } 
    }); 
}); 
相关问题