【问题标题】:Coding a multiple operation calculator in using HTML and Javascript使用 HTML 和 Javascript 编写多运算计算器
【发布时间】:2020-05-06 14:53:06
【问题描述】:

我正在尝试编写一个计算器,用户在其中输入两个数字,然后选择一个操作(+、-、/、*)来执行,这应该会给他们一个结果。我在故障中多次运行代码,并且在我的 JS 中不断收到错误提示 '操作未定义'(参考 JS 中的 if 语句)。谁能解释我在这里做错了什么以及需要改变的地方

HTML

<html lang="en">
  <head>
    <title>CALCULATOR</title>

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css" />

  </head>
  <body>
    <h1>Calculator</h1>


    First Number : <input type="numbers" id="fnum" /><br /><br />
    Second Number : <input type="numbers" id="snum" /><br /><br />

    Operation? :
    <select id="operation">
      <option value="add">+</option>
      <option value="subtract">-</option>
      <option value="divide">/</option>
      <option value="multiply">*</option> </select><br /><br />

    <input type="button" id="Submit" value="Calculate" onclick="calculate()" />

    <script src="script.js"></script>
  </body>
</html>

JS


  var num1 = parseInt(document.getElementById("fnum").value);
  var num2 = parseInt(document.getElementById("snum").value);

  if (operation == 1) {
    var answer = num1 + num2;
    return answer;
  }
  else if (operation == 2) {
    var answer = num1 - num2;
    return answer;
  }
  else if (operation == 3) {
    var answer = num1 / num2;
    return answer;
  }
  else {
    var answer = num1 * num2;
    return answer;
  }

}

【问题讨论】:

标签: javascript html math calculator


【解决方案1】:

你还没有在你的js文件中声明操作变量。在js文件中添加如下代码:

var o= document.getElementById("#operation") 
var operation = o.options[o.selectedIndex].value

#if-else conditions

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2015-05-16
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多