Home > Web Front-end > JS Tutorial > Teach you a trick to implement a simple calculator

Teach you a trick to implement a simple calculator

醉折花枝作酒筹
Release: 2021-04-22 09:16:49
forward
3285 people have browsed it

This article will give you a detailed introduction to the method of implementing a simple calculator in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Teach you a trick to implement a simple calculator

JS implements a simple calculator

Page layout design (HTML CSS)

 due to the previous blog There is a detailed explanation of html and css. Again, I will not go into details and go directly to the code. Because the JQuery selector is used in js, JQuery is introduced in the html using the <script></script> tag. In the html, the calculator event cal() is bound to each button click and the current click object is passed in. this.
  .html file:

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>简单计算器</title>
    <link rel="stylesheet" type="text/css" href="./style.css"> <!-- css样式 -->
   
    <script src="https://code.jquery.com/jquery-latest.min.js"></script> <!-- 引用JQuery库 --></head><body>
    <p>
        <table>
            <tr>
                <td colspan="3"><input type="text" value="0"/></td>
            </tr>
            <tr>
                <td><button id="c11" onclick="cal(this)">+</button></td>
                <td><button id="c12" onclick="cal(this)">-</button></td>
                <td><button id="c13" onclick="cal(this)">×</button></td>
                <td><button id="c14" onclick="cal(this)">/</button></td>
            </tr>
            <tr>
                <td><button id="c21" onclick="cal(this)" value="7">7</button></td>
                <td><button id="c22" onclick="cal(this)" value="8">8</button></td>
                <td><button id="c23" onclick="cal(this)" value="9">9</button></td>
                <td rowspan="2"><button id="c24" onclick="cal(this)">C</button></td>
            </tr>
            <tr>
                <td><button id="c31" onclick="cal(this)" value="4">4</button></td>
                <td><button id="c32" onclick="cal(this)" value="5">5</button></td>
                <td><button id="c33" onclick="cal(this)" value="6">6</button></td>
            </tr>
            <tr>
                <td><button id="c41" onclick="cal(this)" value="1">1</button></td>
                <td><button id="c42" onclick="cal(this)" value="2">2</button></td>
                <td><button id="c43" onclick="cal(this)" value="3">3</button></td>
                <td rowspan="2"><button id="c44" onclick="cal(this)">=</button></td>
            </tr>
            <tr>
                <td colspan="2"><button id="c51" onclick="cal(this)" value="0">0</button></td>
                <td><button id="c53" onclick="cal(this)">.</button></td>
            </tr>
        </table>
    </p>
    <script src = "./calculator.js"></script> <!-- js脚本 --></body></html>
Copy after login

  .css file:

input{
    width: 200px;
    height:50px;
    margin-bottom: 10px;
    padding: 0;
    font:18px bold;}button{
    width: 50px;
    height: 40px;
    margin-bottom: 10px;
    border: 1px dashed black;
    background-color: #ffc4cc;}#c24{
    height: 93px;}#c44{
    height: 93px;}#c51{
    width: 122px;}#c44,#c24,#c14{
    margin-left:10px;}
Copy after login

  Static page as shown:
Teach you a trick to implement a simple calculator

Implement the calculation part ( JS)

1. Function: realize simple addition, subtraction, multiplication and division calculations of numerical values, and clear screen function
2. Operation: For example: 123×29; click 1, 2, 3 ,, click the × sign, click 2, 9 in sequence, and finally click =, you can calculate the result 3567
. The example is shown in the figure: Teach you a trick to implement a simple calculator
Teach you a trick to implement a simple calculator
3. Disadvantages:

  • Negative number calculations cannot be performed, and NaN errors will occur;
  • Cannot perform continuous calculations, and can only perform operations between two numbers at a time; if you want to continue calculations on the previous results, you can directly press Operation symbol and the next number; to start a new calculation, you need to clear the screen first.

4. Idea display:

  • Text box display: Because the content displayed in the text box changes in real time according to the clicked button, in order to make modifications simple, Here we use the JQuery selector to select the text box and assign it to a global variable input. Then we just modify its value according to the val() method of input.

The code is as follows:

var input = $("input");
Copy after login
  • Button id acquisition: Because later we have to perform different operations based on different buttons, so in cal() The first step in the function is to obtain the id of the button, which will be used for subsequent judgment.

The code is as follows:

let btn = e.id;
Copy after login
  • Numerical input: Determine whether it is a number or decimal point based on the id of the button. If so, perform a numeric input operation . First determine whether the value of the current text box is 0. If it is 0, overwrite the input value with the current input; if it is not 0, connect the current input behind the input value.

The code is as follows:

//若input的值为0
input.val(btn_value);//若input的值非0
input.val(input.val()+btn_value);
Copy after login
  • Symbol input: Determine whether it is an arithmetic symbol based on the id of the button. If so, perform the symbol input operation. If continuous operations are not considered, first determine whether the value of the current text box contains, The symbolic link follows the input value.

The code is as follows:

//若input的值含有+、×、/
 alert("连续运算功能未上线!")//若input的值不含有+、×、/
input.val(input.val()+当前运算符号);
Copy after login
  • Numerical calculation: Determine whether it is an equal sign based on the id of the button. If so, perform numerical calculation operations. To make a selection judgment, use the indexOf() method to determine which punctuation mark, ×, / is contained in the input value, and then use the position of the symbol as a separation, use the substring() method to intercept the value in front of the symbol, force it to be converted into a Float type, and then assign it to num1, intercept the value behind the symbol and force it to be converted into Float type and then assign it to num2 to perform corresponding calculations. (Note that the denominator cannot be 0 during division)

The code is as follows:

if(input_value.indexOf("+")!==-1){
        pos = input_value.indexOf("+");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        input.val(num1+num2);
    }
    else  if(input_value.indexOf("-")!==-1){
        pos = input_value.indexOf("-");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        input.val(num1-num2);
    }
    else  if(input_value.indexOf("×")!==-1){
        pos = input_value.indexOf("×");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        input.val(num1*num2);
    }
    else  if(input_value.indexOf("/")!==-1){
        pos = input_value.indexOf("/");
        num1 = parseFloat(input_value.substring(0,pos));
        num2 = parseFloat(input_value.substring(pos+1,input_value.length));
        if(num2-0 === 0){
            alert("分母不能为0!");
        }
        else{
            input.val(num1/num2);
        }
    }
Copy after login
  • Clear screen: Determine whether it is the symbol C according to the id of the button. If so, clear the screen.

The code is as follows:

input.val(0);
Copy after login

5. The JavaScript file is as follows:

"use strict"var input = $("input");function cal(e){
    let btn = e.id;
    //清零
    if( btn === "c24"){
        input.val(0);
    }
    //数值输入
    else if(btn === "c51"||btn === "c41"||btn === "c42"||btn === "c43"
        ||btn === "c31"||btn === "c32"||btn === "c33"
        ||btn === "c21"||btn === "c22"||btn === "c23"){
        let btn_value = document.getElementById(btn).getAttribute("value");
        if( input.val() === "0" ){
            input.val(btn_value);
        }
        else{
            input.val(input.val()+btn_value);
        }
    }
    else if(btn === "c11"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"+");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c12"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"-");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c13"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"×");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c14"){
        let input_value = input.val();
        if(input_value.indexOf("+") === -1&&input_value.indexOf("-") === -1
            &&input_value.indexOf("×") === -1&&input_value.indexOf("/") === -1){
            input.val(input.val()+"/");
        }
        else{
            alert("连续运算功能未上线!")
        }
    }
    else if(btn === "c53"){
        input.val(input.val()+".");
    }
    else if(btn === "c44"){
        let pos,num1,num2;
        let input_value = input.val();
        if(input_value.indexOf("+")!==-1){
            pos = input_value.indexOf("+");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            input.val(num1+num2);
        }
        else  if(input_value.indexOf("-")!==-1){
            pos = input_value.indexOf("-");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            input.val(num1-num2);
        }
        else  if(input_value.indexOf("×")!==-1){
            pos = input_value.indexOf("×");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            input.val(num1*num2);
        }
        else  if(input_value.indexOf("/")!==-1){
            pos = input_value.indexOf("/");
            num1 = parseFloat(input_value.substring(0,pos));
            num2 = parseFloat(input_value.substring(pos+1,input_value.length));
            if(num2-0 === 0){
                alert("分母不能为0!");
            }
            else{
                input.val(num1/num2);
            }

        }
    }}
Copy after login

[Recommended learning: javascript advanced tutorial

The above is the detailed content of Teach you a trick to implement a simple calculator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template