用Javascript计算器

时间:2013-02-26 21:56:44

标签: javascript html calculator

我是初学者并试图在Javascript中编写一个简单的计算器,但有些不对劲。

当用户输入数字“Number 1”和“Number 2”时,应该进行加法,减法,乘法和除法(例如):

Number1 = 5, Number2 = 3
then   => 5 + 3 = 8,
          5 - 3 = 2,
          5 * 3 = 15,
          5 / 3 = 1.6

当用户给出特定等式的数字时,则显示这些操作的结果。

<html>
<head>
<title>Function Calculator</title>
<script type="text/javascript">
   function show_cal(){
    function num(){
    a=Number(document.form1.num1.value);  
    b=Number(document.form1.num2.value); 
    c=a+b;
    document.form1.result1.value=c;

    a=Number(document.form1.num1.value);  
    b=Number(document.form1.num2.value); 
    c=a-b;
    document.form1.result2.value=c;

    a=Number(document.form1.num1.value);  
    b=Number(document.form1.num2.value); 
    c=a*b;
    document.form1.result3.value=c;

    a=Number(document.form1.num1.value);  
    b=Number(document.form1.num2.value); 
    c=a/b;
    document.form1.result4.value=c;
    }

    function addition(){
    a=Number(document.form1.num3.value);  
    b=Number(document.form1.num4.value); 
    c=a+b;
    document.form1.result1.value=c;
    }

    function subtraction(){
    a=Number(document.form1.num5.value);  
    b=Number(document.form1.num6.value); 
    c=a-b;
    document.form1.result2.value=c;
    }

    function multiply(){
    a=Number(document.form1.num7.value);  
    b=Number(document.form1.num8.value); 
    c=a*b;
    document.form1.result3.value=c;
    }

    function division(){
    a=Number(document.form1.num9.value);  
    b=Number(document.form1.num10.value); 
    c=a/b;
    document.form1.result4.value=c;
    }

    /*function formValidator(){
    var number = document.getElementById('number');
        if(isNumeric(number, "Only Numbers pls")){
        return true;
        }return false;
    }

    function notEmpty(elem, helperMsg){ //gia keno
        if(elem.value.length == 0){
            alert(helperMsg);
            elem.focus(); // set the focus to this input
        return false;
        }
    return true;
    }

    function show_clear(){
        document.form1.display.value=null;
        num1= null;
        num2 = null;
        lastaction= null;
        action = null;
    } */
}

</script>
</head>

<body>
<table width="400" align="center" bgcolor="#C0C0C0">
    <form name="form1" action="">

    <tr align="center">
    <td width="600" height="112" align="center" border="1">
        <h1 align="center"> Calculator </h1>
    Number 1: <input name="num1" type="text" size=10/>
    Number 2: <input name="num2" type="text" size=10/>
        </td>
    </tr>

    <tr align="center">
    <td width="500">
    <input name="num3" type="text" size=10/> + 
    <input name="num4" type="text" size=10/> =
    <input name="result1" type="text" size=10/>
    </td>
    </tr>

    <br/>
    <tr align="center">
    <td width="500">
    <input name="num5" type="text" size=10/> -
    <input name="num6" type="text" size=10/> =
    <input name="result2" type="text" size=10/>
    </td>
    </tr>

    <br/>
    <tr align="center">
    <td width="500">
    <input name="num7" type="text" size=10/> *
    <input name="num8" type="text" size=10/> =
    <input name="result3" type="text" size=10/>
    </td>
    </tr>

    <br/>
    <tr align="center">
    <td width="500">
    <input name="num9" type="text" size=10/> /
    <input name="num10" type="text"size=10/> =
    <input name="result4" type="text" size=10/>
    </td>
    </tr>


        <br/>
    <td height="13"></tr>
    <tr align="center" width="100">
    <td>
    <input name="result" type="button" onClick="show_cal()" value="Result" />
    <input type="button" onClick="show_clear()" value="Clear"/>
    </td>
    </tr>

</form>
</table>
</body>
</html>

4 个答案:

答案 0 :(得分:3)

问题是你在函数 show_calc 中有一个函数 sum ,你不会调用这个函数。 完成showcalc函数时需要调用函数num。

<script type="text/javascript">
   function show_cal(){

    function num(){
      a=Number(document.form1.num1.value);  
      b=Number(document.form1.num2.value); 
      c=a+b;
      document.form1.result1.value=c;

      a=Number(document.form1.num1.value);  
      b=Number(document.form1.num2.value); 
      c=a-b;
      document.form1.result2.value=c;

      a=Number(document.form1.num1.value);  
      b=Number(document.form1.num2.value); 
      c=a*b;
      document.form1.result3.value=c;

      a=Number(document.form1.num1.value);  
      b=Number(document.form1.num2.value); 
      c=a/b;
      document.form1.result4.value=c;
    }

    function addition(){
      a=Number(document.form1.num3.value);  
      b=Number(document.form1.num4.value); 
      c=a+b;
      document.form1.result1.value=c;
    }

    function subtraction(){
      a=Number(document.form1.num5.value);  
      b=Number(document.form1.num6.value); 
      c=a-b;
      document.form1.result2.value=c;
    }

    function multiply(){
      a=Number(document.form1.num7.value);  
      b=Number(document.form1.num8.value); 
      c=a*b;
      document.form1.result3.value=c;
    }

    function division(){
      a=Number(document.form1.num9.value);  
      b=Number(document.form1.num10.value); 
      c=a/b;
      document.form1.result4.value=c;
    }

    num();
}

但我有更好的方法来做到这一点。

答案 1 :(得分:3)

您的代码非常混乱并且反复违反DRY(不要重复自己)。是的,你反复重复自己:p

试试这个:

<form action="javascript:void(null);" method="post" onSubmit="calculate(this);">
    <p><label>Number 1: <input type="number" /></label></p>
    <p><label>Number 2: <input type="number" /></label></p>
    <p><input type="submit" value="Calculate" /></p>
    <p>N1 + N2 = <span>-</span></p>
    <p>N1 - N2 = <span>-</span></p>
    <p>N1 * N2 = <span>-</span></p>
    <p>N1 / N2 = <span>-</span></p>
</form>
<script type="text/javascript">
    function calculate(form) {
        var fc = form.children,
            n1 = parseInt(fc[0].children[0].children[0].value || 0,10),
            n2 = parseInt(fc[1].children[0].children[0].value || 0,10);
        fc[3].children[0].firstChild.nodeValue = n1+n2;
        fc[4].children[0].firstChild.nodeValue = n1-n2;
        fc[5].children[0].firstChild.nodeValue = n1*n2;
        fc[6].children[0].firstChild.nodeValue = n1/n2;
    }
</script>

JSFiddle demonstration

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
    <head>
<title>Calculator</title>
<link rel="stylesheet" href="cal.css">
<script src="./calc.js"></script>
    </head>
    <body>
    <div class="calculator">
        <div id="textBox1">
             <input type="text"id="textBox" placeholder="0"/>
        </div>
        <div class="buttons">
        <button class="calc-buttons" onclick="disPlay('1')" value="1">1</button>
        <button class="calc-buttons" onclick="disPlay('2')" value="2">2</button>
        <button class="calc-buttons" onclick="disPlay('3')" value="3">3</button>
        <button class="calc-buttons" onclick="disPlay('4')" value="4">4</button>
        <button class="calc-buttons" onclick="disPlay('5')" value="5">5</button>
        <button class="calc-buttons" onclick="disPlay('6')" value="6">6</button>
        <button class="calc-buttons" onclick="disPlay('7')" value="7">7</button>
        <button class="calc-buttons" onclick="disPlay('8')" value="8">8</button>
        <button class="calc-buttons" onclick="disPlay('9')" value="9">9</button>
        <button class="calc-buttons" onclick="disPlay('0')" value="0">0</button>
        <button class="calc-buttons" onclick="disPlay('+')" value="+">+</button>
        <button class="calc-buttons" onclick="disPlay('-')" value="-">-</button>
        <button class="calc-buttons" onclick="disPlay('*')" value="*">*</button>
        <button class="calc-buttons" onclick="disPlay('/')" value="/">/</button>
        <button class="calc-buttons" onclick="disPlay('%')" value="%">%</button>
        <button class="calc-buttons" onclick="clr()" value="clear">C</button>
        <button class="calc-buttons" onclick="disPlay('.')" value=".">.</button>
        <button class="calc-buttons" onclick="backSpace()" value="B">B</button>
        <button class="calc-buttons-equal" onclick="result()" value="=">=</button>
        </div>
</div>
    </body>
</html>
calc.js:---
var res = "";
function disPlay(x) {
  nan = document.getElementById("textBox").value;
  if (nan === "NaN" || nan === "Infinity" || nan ===  "undefined" || nan === "-Infinity") {   // delete Nan,infinity,undefined after entering the numbers.
    document.getElementById("textBox").value = "";
  }
  if (res && (x >= 0 || x <= 0)) {
    res = false;
    document.getElementById("textBox").value = "";
    document.getElementById("textBox").value += x;

  } else {
    document.getElementById("textBox").value += x;
    res = false;
    var y = [];
    y = document.getElementById("textBox").value;
    p = y.length;
    if ((y[p - 2] === "*" || y[p - 2] === "/" || y[p - 2] === "%" || y[p - 2] === "+" || y[p - 2] === "-" || y[p - 2] === ".") && (x === "*" || x === "/" || x === "%" || x === "+" || x === "-" || x === ".")) {
      document.getElementById("textBox").value = y.slice(0, p - 1);

    }

  }
}

function clr() {
  document.getElementById("textBox").value = "";
}

function backSpace() {
  bakSpa = document.getElementById("textBox").value;
  if (bakSpa === "NaN" || bakSpa === "Infinity" || bakSpa === "undefined" || bakSpa === "-Infinity") {
    document.getElementById("textBox").value = "";
  } else {
    var value = document.getElementById("textBox").value;`enter code here`
    document.getElementById("textBox").value = value.substr(0, value.length - 1);
  }

}

function result() {
  exp = "";
  exp = document.getElementById("textBox").value;
  l = exp.length;
  if (exp[0] == '*' || exp[0] == '/' || exp[0] == '%' || exp[0] == '+' || exp[l - 1] == '+' || exp[l - 1] == '%' || exp[l - 1] == '/' || exp[l - 1] == '*' || exp[l - 1] == '-') {
    document.getElementById("textBox").value = 'NaN';
  } else {
    exp = document.getElementById("textBox").value;
    res = eval(exp);
    console.log(res);
    document.getElementById("textBox").value = res;
    if(res===undefined){
      document.getElementById("textBox").value = "";
    }
  }
}
cal.css:-
*{
    box-sizing: border-box;
    text-align: center;
    padding: 0;
    margin: 0;
}
::placeholder { 
    color: red;
    opacity: 1; 
  }

body {
background: #F6F6F6;
}
.calculator   {
max-width: 400px;
margin: 0 auto;
border: 2px solid #111;
border-radius: 5px;
display:flex;
flex-wrap: wrap;
flex: 0 1 60%;
min-width:400px;
color: #F6F6F6;
}
#calc-buttons ,.calc-buttons {
background-color: gray;
border: none;
color: white;
padding-left: 60px;
padding-top: 15px;
text-decoration: none;
display: inline-flex;
font-size: 16px;
margin: 1px;
cursor: pointer;
width:125px;
height: 50px;
border-radius: 6px;
}
.calc-buttons-equal{
    background-color:orange;
    border: none;
    color: white;
    padding-left: 190px;
    padding-top: 15px;
    text-decoration: none;
    display: inline-flex;
    font-size: 16px;
    margin: 1px;
    cursor: pointer;
    width:388px;
    height: 50px;
    border-radius: 6px;
    }
#textBox1 input   {
background: none;
border: none;
box-shadow: none;
padding: 10px;
width: 100%;
border-bottom: 2px solid #111;
color: #333;
text-align: right;
font-size: 40px;
border-radius: 0;
}

答案 3 :(得分:-2)

<!DOCTYPE html>
<html>
    <head>
        <script>
              z="";  
             fun =""
             ans="";
            function dis(val) 
            { 
                ans = document.getElementById("result").value;
               if (ans === "Infinity" ||ans === "-Infinity" || ans ===  "undefined") {  
                 document.getElementById("result").value = "";
                }
                if(z&& (val >= 0 || val <= 0)){
                    z = false;
                document.getElementById("result").value="";
                document.getElementById("result").value+=val;
                
                }
                else{
                ans = document.getElementById("result").value+=val;
                z = false;
                 var y = [];
                 y = document.getElementById("result").value;
                 p = y.length;
                if ((y[p - 2] ==="*" ||y[p - 2] ==="/" ||y[p - 2] ==="%" ||y[p - 2] ==="+" ||y[p - 2] ==="-" ||y[p - 2] ===".") && (val ==="*" ||val ==="/" ||val ==="%" ||val ==="+" ||val ==="-" ||val ===".")) {
                 document.getElementById("result").value = y.slice(0, p - 2)+y[p-1];

                }
                }
            } 
            function solve() 
            { 
                let i,j;
                i= ans;
                 j=i[i.length-1];
                if(i[0]==="*"||i[0]=="/"||i[0]==="%"||i[0]==="+"){ 
                 document.getElementById("result").value = undefined;
                
                }
               
                else if(j==="*"||j==="/"||j==="%"||j==="."||j==="+"||j==="-"){
                    document.getElementById("result").value = undefined;
                }
              
                else {
                    z="";
                    let x = document.getElementById("result").value; 
                     z = eval(x);
                     if(z===undefined)
                     {
                    document.getElementById("result").value = "";
                     }
                     else{
                        document.getElementById("result").value = z;
                     }
                
            }  
            } 
            function clr() 
            { 
                document.getElementById("result").value ="" 
            } 
            function back() 
              { 
                 var i = document.getElementById("result").value;
                 if(i==="undefined"||i==="infinity"||i==="-infinity"){
                    document.getElementById("result").value ="";
                 }
                 else{
                 document.getElementById("result").value = i.substr(0, i.length - 1);
                 }
                
                 } 
        </script>
        <style>
         * {
             background-color: black;
             height: 100%;
             width: 100%;
             margin: 0px;
             text-align: center;
             box-sizing: border-box;
            
            
         }
         .disply{
               height: 30%;
               width: 100%;
               box-sizing: border-box;
   
         }
         .functions{
             height: 68%;
             width: 100%;
             box-sizing: border-box;
             
            

         }
        
        input{
             background-color:black; 
              border:whitesmoke;
             color: white;
             text-align: center;
             font-size: 45px;
             cursor: pointer;
             height: 20%;
             width: 24.2%;
            
             }
             button{
             background-color:lightslategray; 
             color: white;
             text-align: center;
             font-size: 90px;
             cursor: pointer;
             height: 18%;
             width: 24%;
             border: none;
             border-radius: 50%;
             }
             button[type=button4]{
                width: 48.4%;
                padding-right: 24.2%;            
                border-radius: 40%;
             }
             button[type=button2]{
                 background-color: orange;
                 font-size: 60px;
             }
             button[type=button1]{
                 background-color: whitesmoke;
                 color: black;
                 font-size: 60px;
             }
             input[type=text]{
                height: 100%;
               width: 100%;
               background-color:black;
               text-align: right;
               color: white;
               font-size: 100px;
              
             }
             ::placeholder{
                 color: bisque;
             }
        </style>
    </head>
    <body>
        <div class="disply">
            <input type="text" id="result" placeholder="0"/> 
        </div>
        <div class="functions">
            <button type="button1" value="AC" onclick="clr()">AC</button>
            <button type="button1"value="/" onclick="dis('/')">/</button>
            <button type="button1"value="%" onclick="dis('%')">%</button>
            <button type="button2"value="back" onclick="back()">back</button>
            <button type="button3"value="7" onclick="dis('7')">7</button>
            <button type="button3"value="8" onclick="dis('8')">8</button>
            <button type="button3"value="9" onclick="dis('9')">9</button>
            <button type="button2"value="*" onclick="dis('*')">*</button>
            <button type="button3"value="4" onclick="dis('4')">4</button>
            <button type="button3"value="5" onclick="dis('5')">5</button>
            <button type="button3"value="6" onclick="dis('6')">6</button>
            <button type="button2"value="-" onclick="dis('-')">-</button>
            <button type="button3"value="1" onclick="dis('1')">1</button>
            <button type="button3"value="2" onclick="dis('2')">2</button>
            <button type="button3"value="3" onclick="dis('3')">3</button>
            <button type="button2"value="+" onclick="dis('+')">+</button>
            <button type="button4"value="0" onclick="dis('0')">0</button>
            <button type="button3"value="." onclick="dis('.')">.</button>
            <button type="button2"value="=" onclick="solve()">=</button>
            
        </div>
    </body>
</html>