目前,我有以下下拉菜单:
<select id="dropdown">
<option value="manchester" id="manchester" >Manchester</option>
<option value="leeds" id="leeds">Leeds</option>
<option value="london" id="london">London</option>
</select>
我希望选择此下拉列表以显示该地区的天气。我目前有以下JS。
navigator.geolocation.getCurrentPosition(checked);
var manchester = document.getElementById("manchester").value;
var leeds = document.getElementById("leeds").value;
var london = document.getElementById("london").value;
function checked() {
if (document.getElementById('dropdown').value == manchester) {
var lat = 53.48;
var long = -2.24;
weather(lat, long);
} else if (document.getElementById('dropdown').value == leeds) {
var lat = 53.80;
var long = -1.5491;
weather(lat, long);
} else if (document.getElementById('dropdown').value == london) {
var lat = 51.5074;
var long = -0.12;
weather(lat, long);
}
}
仅当我手动将每个选项的html更改为selected =“ selected”时,此方法才有效。但我真的希望它能使用户选择该选项。似乎当您选择一个选项时,它不会自动识别为选中状态吗?
非常感谢您提供一些帮助,并在可能的情况下对代码的工作方式进行了解释。
答案 0 :(得分:0)
您可以添加事件监听器,以获取带有onchange事件的select标签的值,并使用该值调用显示天气的功能
答案 1 :(得分:0)
所以你可以说:
document.getElementById("dropdown").addEventListener("change",checked)
function checked(e) {
let elm = e.srcElement //this just returns the element which has been changed (the dropdown)
if (elm.value == "manchester") {
var lat = 53.48;
var long = -2.24;
weather(lat, long);
} else if (elm.value == "leeds") {
var lat = 53.80;
var long = -1.5491;
weather(lat, long);
} else if (elm.value == "london") {
var lat = 51.5074;
var long = -0.12;
weather(lat, long);
} }