【发布时间】:2021-08-09 00:40:09
【问题描述】:
我正在尝试使用 JavaScript 在我的天气应用程序中显示来自 OpenWeatherMap 的天气图标。
我尝试过使用 jQuery 和我在网上看到的其他解决方案。我也尝试使用“src”属性指定此链接(“http://openweathermap.org/img/w/”),但链接不起作用,结果图像被破坏。
如何成功地将天气图标添加到我的应用程序中?
这里有一些用于表述这个问题的最小代码。我希望这会有所帮助。
HTML:
<div class="weather">
<div id="date"></div>
<div id="cityName"></div>
<img src="" id="icon">
<div id="temp"></div>
<div id="description"></div>
</div>
JavaScript:
var d = new Date();
var n = d.toLocaleDateString();
document.getElementById("date").innerHTML = n;
function getWeather( cityID ) {
var key = '535f8a50b4bc24608c72fcde2aecb52b';
fetch('https://api.openweathermap.org/data/2.5/weather?id=' + cityID+ '&appid=' + key)
.then(function(resp) { return resp.json() })
.then(function(data) {
drawWeather(data);
})
.catch(function() {
// catch any errors
});
}
window.onload = function() {
getWeather( 6167865 );
}
function drawWeather( d ) {
var celcius = Math.round(parseFloat(d.main.temp)-273.15);
var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
document.getElementById('cityName').innerHTML = d.name;
document.getElementById('description').innerHTML = d.weather[0].description;
document.getElementById('temp').innerHTML = fahrenheit + '°';
document.getElementById('icon').src = "http://openweathermap.org/img/w/"+obj.weather[0].icon+".png";
}
【问题讨论】:
标签: javascript html jquery image api