JavaScript上的计算器(简单)

时间:2017-04-02 17:07:49

标签: javascript

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

<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>

1 个答案:

答案 0 :(得分:0)

您需要获取文本框的值,如下所示:

   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>