对于列表框中的两个元素,我都有一个条件,但无论如何选择,第一个(如果始终)都会触发(以及将列表框切换为其他值)。
我还在一个在线代码游乐场中尝试过该程序,以确保它不是我的设置中所特有的。
的HTML
document.getElementsByName("foodType")[0].addEventListener('change', (event) => {
if (event.target.value == "healthy") {
window.alert("healthy");
}
else if (event.target.value == "fast-food") {} {
window.alert("fast-food");
}
})
<select name="foodType">
<option value="">Food Type</option>
<option value="healthy">healthy</option>
<option value="fast-food">fast food</option>
</select>
最佳答案
您的if else
语句中有语法错误。您需要删除多余的花括号:else if (event.target.value == "fast-food") {} {...
应该else if (event.target.value == "fast-food") {...
document.getElementsByName("foodType")[0].addEventListener('change', (event) => {
console.log(event.target.value);
if (event.target.value == "healthy") {
window.alert("healthy");
} else if (event.target.value == "fast-food") {
window.alert("fast-food");
}
})
<select name="foodType">
<option value="">Food Type</option>
<option value="healthy">healthy</option>
<option value="fast-food">fast food</option>
</select>
关于javascript - 如果条件触发这两种情况,为什么要选择其中之一? (JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59548869/