我正在用 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/