繁体   English   中英

JavaScript上的计算器(简单)

[英]Calculator on JavaScript(simple)

在文本字段中,您需要指定值并通过按钮对其进行计数。 我不明白为什么不这样认为? 您原则上需要通过一个开关来实现它,但我不明白为什么不计算操作数:+,-,*,/

<p>
  <label for="text1">FirstNum</label> 
  <input type="text" id="text1"><br>
  <label for="operation">Operation</label> 
  <input type="text" id="operation"><br>
  <label for="text2">SecondNum</label> 
  <input type="text" id="text2"><br>
  <label for="text3">Result</label> 
  <input type="text" id="text3"><br><br>
  <input type="button" value="ClickResult" onclick="Calc()">
</p>

<script>

  function Calc(operation) {
    //var op;
    switch(operation) {
      case '+':
        text3.value = text1.value + text2.value;
        break;
      case '-':
        text3.value = text1.value - text2.value;
        break;
      case '/':
        text3.value = text1.value / text2.value;
        break;
      case '*':
        text3.value = text1.value * text2.value;
        break;
    }      
 }

</script>

您需要像这样获取文本框的值:

   var text1 = document.getElementById('text1').value;

但是您获得的值是字符串格式,因此您需要将其转换为int或float,因此必须将其转换为int或float,如下所示:

   text1 = parseFloat(text1);

然后在结果框中给出值,如下所示:

document.getElementById('text3').value = result of the calculation

或另一种方式是:

var result = document.getElementById('text3');
result.value = result of computation

 <p> <label for="text1">FirstNum</label> <input type="text" id="text1"><br> <label for="operation">Operation</label> <input type="text" id="operation"><br> <label for="text2">SecondNum</label> <input type="text" id="text2"><br> <label for="text3">Result</label> <input type="text" id="text3"><br><br> <input type="button" value="ClickResult" onclick="Calc()"> </p> <script> function Calc() { var text1 = document.getElementById('text1').value; var text2 = document.getElementById('text2').value; var operation = document.getElementById('operation').value; var text3 = document.getElementById('text3'); text1 = parseFloat(text1); text2 = parseFloat(text2); //var op; switch(operation) { case '+': text3.value = text1 + text2; break; case '-': text3.value = text1 - text2; break; case '/': text3.value = text1 / text2; break; case '*': text3.value = text1 * text2; break; } } </script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM