JavaScript switch 语句只返回第一种情况

标签 javascript html dom

我正在用 vanilla JS 制作一个计算器,在运行 switch 语句对每种情况做不同的事情后,程序只返回第一种情况。

let res = document.getElementById("res")
let sub = document.getElementById("submit")
let sel = document.getElementById("sel")
let opt = sel.options[sel.selectedIndex];

sub.addEventListener("click", () => {
  let inp1 = Number(document.getElementById("input1").value)
  let inp2 = Number(document.getElementById("input2").value)
  switch (opt.value) {
    case "+":
      res.innerHTML = inp1 + inp2;
      break;
    case "-":
      res.innerHTML = inp1 - inp2;
      break;
    case "*":
      res.innerHTML = inp1 * inp2;
      break;
    case "/":
      res.innerHTML = inp1 / inp2;
      break;
    default:
      res.innerHTML = "Please enter something in all of the empty fields";
  }
})
<div>
  <input id="input1" class="input w3-round">
  <select class="dropdown w3-animate-zoom w3-round" id="sel">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
  </select>
  <input id="input2" class="input w3-round">
  <button id="submit" class="w3-button-small w3-round w3-green">Submit</button>
</div>
<p id="res" class="p"></p>

最佳答案

如果您需要在别处使用opt,您可以添加另一个监听器并保留您拥有的:

sel.addEventListener('change', () => {
    opt = sel.options[sel.selectedIndex];
});

这将允许在 sub.click 监听器之外引用 opt

关于JavaScript switch 语句只返回第一种情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57083022/

相关文章:

javascript - 渲染 react 中出现意外标记

javascript - Firebase 数组转换为 AngularChart

javascript - 使用ScrollTop启动JQuery旋钮动画

html - http-equiv ="author"和名称 ="author"有什么区别?

css - 如何为视差图像设置 100% 宽度?

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

javascript - 如何使用 jquery 平滑滚动

javascript - Angular $sce 阻塞了我的音频 blob src

javascript - 菜单隐藏时如何返回className

jQuery 选择器