我从 jquery 和 json 开始,使用 OpenWeatherMap 的 API 开发天气应用程序。我正在尝试通过 icon src 与 img 标签一起显示。我知道以前曾问过类似的问题(这是我的下面代码的模型),但我没有看到 <img>
发生变化经检查。
在我看来,我有<img id="icon" src="#">
,这是我的 jquery:
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
var address = "http://api.openweathermap.org/data/2.5/weather?lat=" + lati +"&lon=" + longi + "&APPID=****";
$.getJSON(address, function(json) {
var iconSrc = "http://openweathermap.org/img/w/" +json.weather.icon +".png";
$('#icon img').attr('src', iconSrc);
});
});
}
});
最佳答案
$('#icon img').attr('src', iconSrc);
选择的示例不正确
您正在尝试选择一个 img
元素,该元素是具有 id 图标的元素的子元素#icon
仅使用 ID 进行选择
$('#icon').attr('src', iconSrc);
记住id应该是唯一的,所以如果你有多个img标签来填充使用类
关于javascript - 使用 jquery 将图像 API src 转换为 <img>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38807612/