【问题标题】:Please explain the reason for this code not working [closed]请解释此代码不起作用的原因[关闭]
【发布时间】:2021-12-30 18:35:31
【问题描述】:

下面给出的代码应该根据输入值给出不同的输出,但它不起作用。

function myFunction() {
  let x = document.getElementById("demo").value;
  let y;
  if (x == "") {
    y = "The field is Empty";
  } else if (isNaN(x)) {
    y = "Input is not a number";
  } else if (x < 5) {
    y = "The number is too low";
  } else(x > 10) {
    y = "The number is too big";
  }
  document.getElementById("p01").innerHTML = y;
}
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

【问题讨论】:

  • } else(x &gt; 10) {,但如果您需要介于 5 和 10 之间的数字,请在数字字段上设置最小/最大和默认值,并告诉用户输入介于 5 和 10 之间的数字跨度>
  • 我希望代码根据给定的输入在 p 标签

    中显示提到的输出。
  • 所以当它是 6 时你希望它显示 undefined?

标签: javascript html if-statement conditional-statements


【解决方案1】:

您在else 语句中设置了一个条件:else (x &gt; 10),这是无法完成的。将其更改为else if (x &gt; 10),您应该一切顺利。

【讨论】:

  • 感谢您的帮助。它按我想要的方式工作。
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 2018-04-01
  • 2015-05-11
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
相关资源
最近更新 更多