我正在尝试使用JS制作计算器,但是我的代码无法正常工作,我不知道为什么。我需要咨询

时间:2019-12-29 18:51:37

标签: javascript html forms calculator

这是一个使用表单类型来创建计算器的JS程序。 由于某种原因(我不知道),我在运行该代码时不执行任何操作。 我希望获得帮助,以了解我做错了什么以及如何修复该程序。 该程序的工作方式如下:运行该程序时,屏幕上会出现数字(0-9),您可以用它们组成2个数字。还有其他一些按钮可以帮助进行计算-点按钮用于生成数字,如4.2; C按钮用于重置用户创建的数字;操作按钮,您可以用它们减去,连接,乘和除数字;还有一个计算按钮,用于计算用户输入的所有数据(在计算按钮下方,有两个输出,指示输入到计算器中的两个数字)。例如,对于输入6,。,5、4,*,7,输出应为6.54 * 7 = 45.78。

<!DOCTYPE html>
        <html>
            <head>
                <script>
                    function add(num){ <!--builds the numbers which I'm using to calculate the result-->
        <!--I was trying to learn the material myself because my teacher pretty sucks so probably I did a basic mistake which is most likely here-->
                    var number1 = document.getElementById("no_1").value; 
                    var number2 = document.getElementById("no_2").value; 
                    if(document.getElementById("+").clicked || document.getElementById("-").clicked || 
                        document.getElementById("*").clicked || document.getElementById("/").clicked) <--checks if the user finish to write the first num and pass to the next one-->
                        document.getElementById("no_2").id = number2 + num;
                        else
                            document.getElementById("no_1").id = number1 + num; 
                    } 
                    function clear(){ <!--reset the numbers-->
                        document.frm.no_1.id = 0;
                        document.frm.no_2.id = 0;
                    }
                    function calc(){ <!--calculate the result by using the numbers the "add" method built and write the formule x?y=? which enters to "total" and printed-->
        <!--same thing here, too-->
                        var number1 = parseInt(document.getElementById("no_1").value); 
                        var number2 = parseInt(document.getElementById("no_2").value); 
                        if(document.getElementById("+").clicked){
                        var sum = number1 + number2;
                        document.frm.total.id = number1+"+"+number2+"="+sum;
                        }
                        else{ 
                            if(document.getElementById("-").clicked){
                                var sum = number1 - number2;
                                    document.frm.total.id = number1+"-"+number2+"="+sum;
                            }
                            else{ 
                                if(document.getElementById("*").clicked){
                                    var sum = number1 * number2;
                                    document.frm.total.id = number1+"*"+number2+"="+sum;
                                }
                                else{
                                    var sum = number1 / number2;
                                    document.frm.total.id = number1+"/"+number2+"="+sum;
                                }
                            }
                        }
                    }

                </script>
            </head>
            <body>
                <div style="border: solid black 5px ; width: 20% ; position:absolute ; top: 25% ; right: 40%">
                    <form name="frm">
                        <input type="button" id="1" value="1" onclick="add(1)"> <input type="button" id="2" value="2" onclick="add(2)"> 
                        <input type="button" id="3" value="3" onclick="add(3)"> <input type="button" id="+" value="&nbsp;+&nbsp;">
                        <br>
                        <input type="button" id="4" value="4" onclick="add(4)"> <input type="button" id="5" value="5" onclick="add(5)"> 
                        <input type="button" id="6" value="6" onclick="add(6)"> <input type="button" id="-" value="&nbsp;-&nbsp;">
                        <br>
                        <input type="button" id="7" value="7" onclick="add(7)"> <input type="button" id="8" value="8" onclick="add(8)"> 
                        <input type="button" id="9" value="9" onclick="add(9)"> <input type="button" id="*" value="&nbsp;*&nbsp;">
                        <br>
                        <input type="button" id="dot" value=". " onclick="add(.)">   <input type="button" id="0" value="0" onclick="add(0)"> 
                        <input type="button" id="clear" value="c" onclick="clear()"> <input type="button" id="/" value="&nbsp;/&nbsp;">
                        <br>
                        number 1 = <input type="text" id="no_1" size="1"> number 2 = <input type="text" id="no_2" size="1">
                        <br>
                        <input type="button" id="calc" value="     calculate     " onclick="calc()">
                        <br>
                        <input type="text" id="total" size="13">
                    </form>
                </div>
            </body>
        </html>

1 个答案:

答案 0 :(得分:0)

固定程序

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>a Calc...</title>
  <style>
    #f-calc {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 16px;
      border: 5px solid black;
      padding: 1em;
      width: 12em;
      margin: 2em auto;
      border-radius: .8em;
    }
    #f-calc button {
      display: inline-block;
      border: 1px solid lightgrey;
      width: 2.8em;
      height: 2.4em;
      margin: .2em;
      font-weight: bold;
    }
    #f-calc button:nth-child(4n) {
      margin-left: .5em;
    }
    #f-calc span {
      margin-top: .3em;
      font-size: 12px;
      margin-right: .3em;
    }
    #f-calc input {
      margin-top: .3em;
      width: 9em;
      height: 1.8em;
      padding-right: .3em;
      text-align: right;
      display: inline-block;
      border: 1px solid lightgrey;
    }
    #f-calc button[value=calc] {
      width: 14em;
      margin-top: .7em;
    }
    #f-calc output {
      display: block;
      width: 12em;
      margin-top: .3em;
      height: 1.2em;
      text-align: right;
      border-bottom: 1px solid grey;
    }
    .current {
      color: darkblue;
      font-weight: bold;
      border-color: darkblue !important;
    }
  </style>
</head>
<body>
  <div id="f-calc">
    <button value="1">1</button> <button value="2">2</button> <button value="3">3</button>   <button value="+">+</button>
    <button value="4">4</button> <button value="5">5</button> <button value="6">6</button>   <button value="-">-</button>
    <button value="7">7</button> <button value="8">8</button> <button value="9">9</button>   <button value="*">x</button>
    <button value=".">.</button> <button value="0">0</button> <button value="c">c</button>   <button value="/">/</button>

    <span>Number 1:</span> <input type="text" value="0" id="in-1" readonly >
    <span>Number 2:</span> <input type="text" value="0" id="in-2" readonly >

    <button value="calc">calculate ( + )</button>

    <output></output>
  </div>

  <script>
    const fCalc  = document.getElementById('f-calc')
      ,   total  = fCalc.querySelector('output')
      ,   btCalc = fCalc.querySelector('button[value=calc]')
      ,   inVal  = [ { elm: document.getElementById('in-1')  }
                   , { elm: document.getElementById('in-2')  }
                   ]
      ;
    let current_inVal = 0
      , operation     = '+'
      ;
    function setInVal()
      {
      inVal[0].elm.className = (current_inVal===0)?'current':'';
      inVal[1].elm.className = (current_inVal===1)?'current':'';
      }
    setInVal()
      ;
    fCalc.onclick=e=>
      {
      if (e.target.matches('input'))
        {
        current_inVal = inVal.findIndex(x=>x.elm.id=== e.target.id);
        setInVal();
        }
      if (!e.target.matches('button')) return
        ;
      total.textContent = '';                 // in any cases
      if (!isNaN(parseInt(e.target.value)) )  // numeric entry only
        {
        inVal[current_inVal].elm.value = (parseFloat(inVal[current_inVal].elm.value + e.target.value));
        }
      else
        {
        switch (e.target.value)  // operations..
          {
          case 'calc':
            total.textContent = eval(`${inVal[0].elm.value} ${operation} ${inVal[1].elm.value}`);
            break;
          case 'c':
            inVal[current_inVal].elm.value = 0;
            break;
          case '.':
            if ( inVal[current_inVal].elm.value.indexOf('.')===-1 ) // only one is possible
              {
              inVal[current_inVal].elm.value += '.'
              }
            break;
          default:  // this is '+' or '-' or '*' or '/'
            operation     = e.target.value;
            current_inVal = ++current_inVal %2;
            setInVal();
            btCalc.textContent = `calculate ( ${e.target.textContent} )`;
            break;
          }
        }
      }
  </script>
</body>
</html>

测试代码段

const fCalc  = document.getElementById('f-calc')
  ,   total  = fCalc.querySelector('output')
  ,   btCalc = fCalc.querySelector('button[value=calc]')
  ,   inVal  = [ { elm: document.getElementById('in-1')  }
                , { elm: document.getElementById('in-2')  }
                ]
  ;
let current_inVal = 0
  , operation     = '+'
  ;
function setInVal()
  {
  inVal[0].elm.className = (current_inVal===0)?'current':'';
  inVal[1].elm.className = (current_inVal===1)?'current':'';
  }
setInVal()
  ;
fCalc.onclick=e=>
  {
  if (e.target.matches('input'))
    {
    current_inVal = inVal.findIndex(x=>x.elm.id=== e.target.id);
    setInVal();
    }
  if (!e.target.matches('button')) return
    ;
  total.textContent = '';                 // in any cases
  if (!isNaN(parseInt(e.target.value)) )  // numeric entry only
    {
    inVal[current_inVal].elm.value = (parseFloat(inVal[current_inVal].elm.value + e.target.value));
    }
  else
    {
    switch (e.target.value)  // operations..
      {
      case 'calc':
        total.textContent = eval(`${inVal[0].elm.value} ${operation} ${inVal[1].elm.value}`);
        break;
      case 'c':
        inVal[current_inVal].elm.value = 0;
        break;
      case '.':
        if ( inVal[current_inVal].elm.value.indexOf('.')===-1 ) // only one is possible
          {
          inVal[current_inVal].elm.value += '.'
          }
        break;
      default:  // this is '+' or '-' or '*' or '/'
        operation     = e.target.value;
        current_inVal = ++current_inVal %2;
        setInVal();
        btCalc.textContent = `calculate ( ${e.target.textContent} )`;
        break;
      }
    }
  }
#f-calc {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  border: 5px solid black;
  padding: 1em;
  width: 12em;
  margin: 2em auto;
  border-radius: .8em;
}
#f-calc button {
  display: inline-block;
  border: 1px solid lightgrey;
  width: 2.8em;
  height: 2.4em;
  margin: .2em;
  font-weight: bold;
}
#f-calc button:nth-child(4n) {
  margin-left: .5em;
}
#f-calc span {
  margin-top: .3em;
  font-size: 12px;
  margin-right: .3em;
}
#f-calc input {
  margin-top: .3em;
  width: 9em;
  height: 1.8em;
  padding-right: .3em;
  text-align: right;
  display: inline-block;
  border: 1px solid lightgrey;
}
#f-calc button[value=calc] {
  width: 14em;
  margin-top: .7em;
}
#f-calc output {
  display: block;
  width: 12em;
  margin-top: .3em;
  height: 1.2em;
  text-align: right;
  border-bottom: 1px solid grey;
}
.current {
  color: darkblue;
  font-weight: bold;
  border-color: darkblue !important;
}
<div id="f-calc">
  <button value="1">1</button> <button value="2">2</button> <button value="3">3</button>   <button value="+">+</button>
  <button value="4">4</button> <button value="5">5</button> <button value="6">6</button>   <button value="-">-</button>
  <button value="7">7</button> <button value="8">8</button> <button value="9">9</button>   <button value="*">x</button>
  <button value=".">.</button> <button value="0">0</button> <button value="c">c</button>   <button value="/">/</button>

  <span>Number 1:</span> <input type="text" value="0" id="in-1" readonly >
  <span>Number 2:</span> <input type="text" value="0" id="in-2" readonly >

  <button value="calc">calculate ( + )</button>

  <output></output>
</div>