使用javascript实现四则运算计算器

2018-09-17  本文已影响0人  田小田txt
四则计算器效果图.png
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript">
      function validate(str){
  var reg = /^\d+$/;              
  if (!reg.test(str)){                  
    alert("请输入数字");
      }
   }
   function calculator(){
    var pre=document.getElementById("pre").value;
    var next=document.getElementById("next").value;
    var opra=document.getElementById("operator").value;

    var result=0;
    switch(opra) {
    case "+":
    result=parseInt(pre)+parseInt(next);
         break;
    case "-":
    result=parseInt(pre)-parseInt(next);
        break;
    case "*":
        result=parseInt(pre)*parseInt(next);
        break;
    case "/":
        if(parseInt(next)!=0){
            result=parseInt(pre)/parseInt(next);
        }
        else{
            alert("除数不能为0");
            return;
        }
        break;
    default:
        break;
}
  document.getElementById("result").value=result;
}

</script>
</head>
<body>
<input type="text" name="text" id="pre" onblur="validate(this.value);">
<select  id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="text" id="next" onblur="validate(this.value);">
<span>=</span>
<input type="text" id="result" readonly="true">
<input type="button" id="btn" value="提交" onclick="calculator();">
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读