【问题标题】:Why JS can't read value property in calculator application? [closed]为什么 JS 不能在计算器应用程序中读取 value 属性? [关闭]
【发布时间】:2020-07-01 01:12:18
【问题描述】:

我正在做一个计算器。 Inspector 告诉我它无法在我的 JS 的第 4 行读取 value 的属性。

我已经逐行浏览,但我无法弄清楚我做错了什么。 我在 YouTube 上关注 mmtutusthis tutorial

我浏览了每一行,我的代码与他的相同。

function calc() {
  var a = parseInt(document.querySelector("#value1").value);
  var b = parseInt(document.querySelector("#value2").value);
  var op = document.querySelector("#operator").value;
  var calculate;

  if (op == "add") {
    calculate = a + b;
  } else if (op == "min") {
    calculate = a - b;
  } else if (op == "div") {
    calculate = a / b;
  } else if (op == "mul") {
    calculate = a * b;
  }

  document.querySelector("#result").innerHTML = calculate;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <form>
    Value 1: <input type="text" id="value1" /> Value 2:
    <input type="text" id="value2" /> Operator:
    <select>
      <option value="add"> Add </option>
      <option value="min"> Subtract </option>
      <option value="div"> Divide </option>
      <option value="mul"> Multiply </option>
    </select>
    <button type="button" onclick="calc()">Calculate</button>
  </form>

  <div id="result"></div>
</body>

<script src="main.js"></script>

</html>

您能帮我找出问题的根源吗?

【问题讨论】:

  • document.querySelector("#operator") - 您的 HTML 中没有任何 ID 为 "operator" 的元素。
  • var op = document.querySelector("#value2").value;
  • 你需要&lt;select id="operator"&gt;
  • @Barmar 你刚刚看了那个 youtube 视频吗?
  • 视频中的时间是 05:00

标签: javascript html calculator


【解决方案1】:

您尚未使用“操作员”指定类名或 id-name,因此无法找到该元素。

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2021-09-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多