3 回答
![?](http://img1.sycdn.imooc.com/5458463b0001358f02200220-100-100.jpg)
TA贡献2003条经验 获得超2个赞
更新
对不起,我的最后一个答案是我在没有测试的情况下盲目发布的。另外,不加解释。感谢评论者。
通过绑定选项使用
for (index in countryCodes) {
select.options[select.options.length] = new Option(countryCodes[index], index);
}
您将在下拉列表中得到“AF”、“AX”、“AL”……等等。导致例如“AF”作为元素的值和对应的“阿富汗”作为选择元素的文本。
所以,这是你真正需要的@Rogozin:
$("#weather-button").click(function() {
$(".weather-img").html("");
$(".weather-type").html("");
$(".weather-temp").html("");
var city = $("input[name=city-box]").val();
var region = "";
var selected = document.getElementById("country-select");
if (selected.value != -1) {
region = selected.value; // if you want value "AF" to send
// OR
region = selected.options[selected.selectedIndex].text; // if you want "Afghanistan" to send
}
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + region + "&units=metric&myapikey", function(data) {
console.log(data);
});
});
![?](http://img1.sycdn.imooc.com/5458502c00012d4a02200220-100-100.jpg)
TA贡献1848条经验 获得超10个赞
尝试在 jquery 上使用onchange属性或更改事件
<form>
Select Character:
<select id="mySelect" onchange="myFunction()">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
</form>
<p id="demo"></p>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = x;
}
![?](http://img1.sycdn.imooc.com/5333a1920001d36402200220-100-100.jpg)
TA贡献1859条经验 获得超6个赞
我想你在找这个
$.getJSON("https://restcountries.eu/rest/v2/all", function(countryData) {
var countryCodes = countryData.map(item => `<option value="${item.alpha2Code}">${item.name}</option>`);
$("#country-select")
.html('<option value="">Country</option>')
.append(countryCodes.join(""));
})
$("#country-select").on("change", function() {
console.log(this.value)
})
$("#weather-button").click(function() {
$(".weather-img").html("");
$(".weather-type").html("");
$(".weather-temp").html("");
var city = $("input[name=city-box]").val();
var region = $("#country-select").val() || "whatever is default country code";
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + region + "&units=metric&myapikey", function(data) {
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country-select"></select>
添加回答
举报