我正在从天气 API 获取 JSON 数据。目前,我的代码从 html 输入获取城镇名称并查询 API 以获取该特定地点的天气。我为国家/地区代码引入了一个选择元素(因此,如果您想查看美国那不勒斯而不是意大利那不勒斯的天气,则必须在下拉菜单中选择美国代码)。我希望它在启动搜索之前检查是否选择了国家/地区代码,如果是,则将其添加到查询的参数中。
我尝试了一些 if/else 语句但没有成功。国家/地区代码存储在一个对象中并且不是硬编码的。我从不同的 API 获取对象。我已设法将这些代码放入 select 元素中,但现在我需要确保搜索考虑是否选择了不同的国家/地区。
如果用户选择了一个,我希望区域变量包含国家代码
// CODE THAT ADDS WEATHER DATA INTO DOM //
$("#weather-button").click(function() {
$(".weather-img").html("");
$(".weather-type").html("");
$(".weather-temp").html("");
var city = $("input[name=city-box]").val();
var region = "";
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + region + "&units=metric&myapikey", function(data) {
console.log(data);..........................
});
// HOW IM GETTING COUNTRY CODE DATA //
var countryCodes = [];
$.getJSON("https://restcountries.eu/rest/v2/all", function(countryData) {
var countryCodes = countryData.reduce((countries, item) => {
countries[item.name] = item.alpha2Code;
return countries;
}, {});
console.log(countryCodes);
// HOW IVE ADDED COUNTRY CODE DATA TO THE <SELECT> //
var selectBox = $("#country-select");
var select = document.getElementById("country-select");
selectBox.append($('<option>', {
value: -1,
text: 'Select a Country'
}));
for (index in countryCodes) {
select.options[select.options.length] = new Option(countryCodes[index], index);
}
})
})
湖上湖
慕桂英546537
BIG阳
相关分类