【问题标题】:Anyway to shorten code inside if statement JavaScript无论如何要缩短 if 语句 JavaScript 中的代码
【发布时间】:2022-11-01 22:21:27
【问题描述】:

有没有办法缩短 JavaScript 中 if 语句中的代码,我正在考虑 for 循环,但我不知道如何以及是否可能。我已经把我认为的相关代码

var operators = document.querySelectorAll(".operators button");
var string = screenInput.innerHTML
var lastCharacter = string[string.length - 1]
console.log(lastCharacter)

if (lastCharacter === "+") {
  document.getElementById("subtract-operator").disabled = true
  document.getElementById("multiply-operator").disabled = true
  document.getElementById("divide-operator").disabled = true
}
<div class="operators">
  <button id="add-operator">+</button>
  <button id="subtract-operator">-</button>
  <button id="multiply-operator">*</button>
  <button id="divide-operator">/</button>
</div>

【问题讨论】:

  • 是只有这个if 语句,还是每个运算符都有语句(禁用其他运算符按钮)?

标签: javascript button


【解决方案1】:

你得到的代码没有什么特别的问题,但如果你确实想干掉重复使用getElementById('x').disabled,那么循环就是这样做的方法。

document.querySelectorAll('#subtract-operator, #multiply-operator, #divide-operator')
  .forEach(el => el.disabled = true);

更好的是,在所有这些元素上放置一个类并按该单个类进行选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    相关资源
    最近更新 更多