javascript - 如果条件触发这两种情况,为什么要选择其中之一? (JavaScript

标签 javascript

对于列表框中的两个元素,我都有一个条件,但无论如何选择,第一个(如果始终)都会触发(以及将列表框切换为其他值)。

我还在一个在线代码游乐场中尝试过该程序,以确保它不是我的设置中所特有的。

的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/

相关文章:

javascript - 在 React 中单击链接时关闭下拉菜单的最佳实践是什么?

javascript - javascript中的拆分方法?

javascript - 如何为 true 和 false 添加输入文本验证?

javascript - 我如何将按钮向上移动?

javascript - 在字段旁边显示图像

javascript - 检查复选框的状态

javascript - D3 力图 - 固定不重叠的节点

javascript - 表行操作的 React redux 最佳实践

javascript - polymer :未捕获类型错误:无法读取未定义的属性 'persistent'

javascript - iframe点击后才显示?