zoukankan      html  css  js  c++  java
  • JS实现简易计算器的7种方法

    先放图(好吧比较挫)

    方法一:最容易版

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" onclick="addHandler();" />
            <input type="button" value="-" onclick="subtractHandler();" />
            <input type="button" value="×" onclick="multiplyHandler();" />
            <input type="button" value="÷" onclick="divideHandler();" />
        </p>
    </div>
    
    <script> 
            // 获取元素
            var calculator = document.querySelector('#calculator');
            var formerInput = calculator.querySelector('.formerInput');
            var laterInput = calculator.querySelector('.laterInput');
            var sign = calculator.querySelector('.sign');
            var resultOutput = calculator.querySelector('.resultOutput');
    
            //
            function addHandler() {
                sign.innerHTML = '+';
                resultOutput.innerHTML = +formerInput.value + +laterInput.value;
            }
            //
            function subtractHandler() {
                sign.innerHTML = '-';
                resultOutput.innerHTML = formerInput.value - laterInput.value;
            }
            //
            function multiplyHandler() {
                sign.innerHTML = '×';
                resultOutput.innerHTML = formerInput.value * laterInput.value;
            }
            //
            function divideHandler() {
                sign.innerHTML = '÷';
                resultOutput.innerHTML = formerInput.value / laterInput.value;
            }
    </script>
    </body>
    </html>

    方法二:结构和行为分离

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" onclick="addHandler();" />
            <input type="button" value="-" onclick="subtractHandler();" />
            <input type="button" value="×" onclick="multiplyHandler();" />
            <input type="button" value="÷" onclick="divideHandler();" />
        </p>
    </div>
    
    <script>
            // 获取元素
            var calculator = document.querySelector('#calculator');
            var formerInput = calculator.querySelector('.formerInput');
            var laterInput = calculator.querySelector('.laterInput');
            var sign = calculator.querySelector('.sign');
            var resultOutput = calculator.querySelector('.resultOutput');
            var btns = calculator.querySelectorAll('.btn');
    
            // 绑定事件
            // +
            btns[0].onclick = addHandler;
            // -
            btns[1].onclick = subtractHandler;
            // ×
            btns[2].onclick = multiplyHandler;
            // ÷
            btns[3].onclick = divideHandler;
    
            //
            function addHandler() {
                sign.innerHTML = '+';
                resultOutput.innerHTML = +formerInput.value + +laterInput.value;
            }
            //
            function subtractHandler() {
                sign.innerHTML = '-';
                resultOutput.innerHTML = formerInput.value - laterInput.value;
            }
            //
            function multiplyHandler() {
                sign.innerHTML = '×';
                resultOutput.innerHTML = formerInput.value * laterInput.value;
            }
            //
            function divideHandler() {
                sign.innerHTML = '÷';
                resultOutput.innerHTML = formerInput.value / laterInput.value;
            }
    </script>
    </body>
    </html>

    方法三:循环绑定事件

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" onclick="addHandler();" />
            <input type="button" value="-" onclick="subtractHandler();" />
            <input type="button" value="×" onclick="multiplyHandler();" />
            <input type="button" value="÷" onclick="divideHandler();" />
        </p>
    </div>
    
    <script>
            // 获取元素
            var calculator = document.querySelector('#calculator');
            var formerInput = calculator.querySelector('.formerInput');
            var laterInput = calculator.querySelector('.laterInput');
            var sign = calculator.querySelector('.sign');
            var resultOutput = calculator.querySelector('.resultOutput');
            var btns = calculator.querySelectorAll('.btn');
    
            // 绑定事件
            for (var i = 0; i < btns.length; i++) {
                btns[i].onclick = function () {
                    switch (this.title) {
                        case 'add':
                            addHandler();
                            break;
                        case 'subtract':
                            subtractHandler();
                            break;
                        case 'multiply':
                            multiplyHandler();
                            break;
                        case 'divide':
                            divideHandler();
                            break;
                    }
                };
            }
    
            //
            function addHandler() {
                sign.innerHTML = '+';
                resultOutput.innerHTML = +formerInput.value + +laterInput.value;
            }
            //
            function subtractHandler() {
                sign.innerHTML = '-';
                resultOutput.innerHTML = formerInput.value - laterInput.value;
            }
            //
            function multiplyHandler() {
                sign.innerHTML = '×';
                resultOutput.innerHTML = formerInput.value * laterInput.value;
            }
            //
            function divideHandler() {
                sign.innerHTML = '÷';
                resultOutput.innerHTML = formerInput.value / laterInput.value;
            }
    </script>
    </body>
    </html>

    方法四:提取函数

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" class="btn" title="add" />
            <input type="button" value="-" class="btn" title="subtract" />
            <input type="button" value="×" class="btn" title="multiply" />
            <input type="button" value="÷" class="btn" title="divide" />
        </p>
    </div>
    
    <script>
            // 获取元素
            var calculator = document.querySelector('#calculator');
            var formerInput = calculator.querySelector('.formerInput');
            var laterInput = calculator.querySelector('.laterInput');
            var sign = calculator.querySelector('.sign');
            var resultOutput = calculator.querySelector('.resultOutput');
            var btns = calculator.querySelectorAll('.btn');
    
            // 绑定事件
            each(btns, function (index, elem ) {
                elem.onclick = function () {
                    switch (this.title) {
                        case 'add':
                            addHandler();
                            break;
                        case 'subtract':
                            subtractHandler();
                            break;
                        case 'multiply':
                            multiplyHandler();
                            break;
                        case 'divide':
                            divideHandler();
                            break;
                    }
                };
            });
            
            // 遍历
            function each(array, fn) {
                for (var i = 0; i < array.length; i++) {
                    fn(i, array[i]);
                }
            }
    
            // 更新符号
            function updateSign(symbol) {
                sign.innerHTML = symbol;
            }
    
            // 加法
            function add(num1, num2) {
                return +num1 + +num2;
            }
            // 减法
            function subtract(num1, num2) {
                return num1 - num2;
            }
            // 乘法
            function multiply(num1, num2) {
                return num1 * num2;
            }
            // 除法
            function divide(num1, num2) {
                return num1 / num2;
            }
    
            // 输出结果
            function outputResult(result) {
                resultOutput.innerHTML = result;
            }
    
            //
            function addHandler() {
                // sign.innerHTML = '+';
                updateSign('+');
                outputResult(add(formerInput.value, laterInput.value));
            }
            //
            function subtractHandler() {
                updateSign('-');
                outputResult(subtract(formerInput.value, laterInput.value));
            }
            //
            function multiplyHandler() {
                updateSign('×');
                outputResult(multiply(formerInput.value, laterInput.value));
            }
            //
            function divideHandler() {
                updateSign('÷');
                outputResult(divide(formerInput.value, laterInput.value));
            }
    </script>
    </body>
    </html>

    方法五:管理代码(找到组织)

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" class="btn" title="add" />
            <input type="button" value="-" class="btn" title="subtract" />
            <input type="button" value="×" class="btn" title="multiply" />
            <input type="button" value="÷" class="btn" title="divide" />
        </p>
    </div>
    
    <script>
                // 获取元素
                var wrapElem = document.querySelector('#calculator');
                var calculatorElem = {
                    formerInput: wrapElem.querySelector('.formerInput'),
                    laterInput: wrapElem.querySelector('.laterInput'),
                    sign: wrapElem.querySelector('.sign'),
                    resultOutput: wrapElem.querySelector('.resultOutput'),
                    btns: wrapElem.querySelectorAll('.btn')
                };
    
                // 绑定事件
                each(calculatorElem.btns, function (index, elem    ) {
                    elem.onclick = function () {
                        switch (this.title) {
                            case 'add':
                                addHandler();
                                break;
                            case 'subtract':
                                subtractHandler();
                                break;
                            case 'multiply':
                                multiplyHandler();
                                break;
                            case 'divide':
                                divideHandler();
                                break;
                        }
                    };
                });
                
                // 遍历
                function each(array, fn) {
                    for (var i = 0; i < array.length; i++) {
                        fn(i, array[i]);
                    }
                }
    
                // 更新符号
                function updateSign(symbol) {
                    calculatorElem.sign.innerHTML = symbol;
                }
    
                var operation = {
                    add: function(num1, num2) {
                        return +num1 + +num2;
                    },
                subtract: function(num1, num2) {
                        return num1 - num2;
                    },
                multiply: function(num1, num2) {
                        return num1 * num2;
                    },
                divide: function(num1, num2) {
                        return num1 / num2;
                    }
                };
    
                // 输出结果
                function outputResult(result) {
                    calculatorElem.resultOutput.innerHTML = result;
                }
    
                //
                function addHandler() {
                    // sign.innerHTML = '+';
                    updateSign('+');
                    outputResult(operation.add(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                }
                //
                function subtractHandler() {
                    updateSign('-');
                    outputResult(operation.subtract(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                }
                //
                function multiplyHandler() {
                    updateSign('×');
                    outputResult(operation.multiply(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                }
                //
                function divideHandler() {
                    updateSign('÷');
                    outputResult(operation.divide(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                }
    </script>
    </body>
    </html>

    方法六:OCP开放--封闭原则

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" class="btn" title="add" />
            <input type="button" value="-" class="btn" title="subtract" />
            <input type="button" value="×" class="btn" title="multiply" />
            <input type="button" value="÷" class="btn" title="divide" />
            <input type="button" value="%" class="btn" title="mod" />
            <input type="button" value="^" class="btn" title="power" />
            <!-- <input type="button" value="1/x" class="btn" title="invert" /> -->
        </p>
    </div>
    
    <script>
        // 获取元素
        var wrapElem = document.querySelector('#calculator');
        var calculatorElem = {
            formerInput: wrapElem.querySelector('.formerInput'),
            laterInput: wrapElem.querySelector('.laterInput'),
            sign: wrapElem.querySelector('.sign'),
            resultOutput: wrapElem.querySelector('.resultOutput'),
            btns: wrapElem.querySelectorAll('.btn')
        };
    
        // 绑定事件
        each(calculatorElem.btns, function (index, elem    ) {
                elem.onclick = function () {
                    updateSign(this.value);
                    outputResult(operate(this.title, calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                };
        });
        
        // 遍历
        function each(array, fn) {
            for (var i = 0; i < array.length; i++) {
                fn(i, array[i]);
            }
        }
    
        // 更新符号
        function updateSign(symbol) {
            calculatorElem.sign.innerHTML = symbol;
        }
    
        // 运算
        function operate(name, num1, num2) {
                if (!operation[name]) throw new Error('不存在名为' + name + '的运算方法!');
                return operation[name](num1, num2);
        }
    
        var operation = {
            add: function(num1, num2) {
                return +num1 + +num2;
            },
            subtract: function(num1, num2) {
                    return num1 - num2;
                },
            multiply: function(num1, num2) {
                    return num1 * num2;
                },
            divide: function(num1, num2) {
                    return num1 / num2;
                },
                addOperation: function (name, fn) {
                    if (!this[name]) {
                        this[name] = fn;
                    }
                    return this;
                }
        };
    
        operation.addOperation('mod', function (num1, num2) {
            return num1 % num2;
        }).addOperation('power', function (base, power) {
            return Math.pow(base, power);
        });
    
        // 输出结果
        function outputResult(result) {
            calculatorElem.resultOutput.innerHTML = result;
        }
    </script>
    </body>
    </html>

    方法七:模块化

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <title>简易计算器</title>
    <style>
        body {
            background-color: #eee;
        }
        #calculator {
            margin: 100px 0 0 150px;
        }
    </style>
    </head>
    <body>
    
    <!-- 简易计算器 -->
    <div id="calculator">
        <p>
            <input type="text" class="formerInput" value="1" />
            <span class="sign">+</span>
            <input type="text" class="laterInput" value="1" />
            <span>=</span>
            <span class="resultOutput">2</span>
        </p>
        <p>
            <input type="button" value="+" class="btn" title="add" />
            <input type="button" value="-" class="btn" title="subtract" />
            <input type="button" value="×" class="btn" title="multiply" />
            <input type="button" value="÷" class="btn" title="divide" />
            <input type="button" value="%" class="btn" title="mod" />
            <input type="button" value="^" class="btn" title="power" />
            <input type="button" value="1/x" class="btn" title="invert" />
        </p>
    </div>
    
    <script>
    
        (function () {
            // 获取元素
            var wrapElem = document.querySelector('#calculator');
            var calculatorElem = {
                formerInput: wrapElem.querySelector('.formerInput'),
                laterInput: wrapElem.querySelector('.laterInput'),
                sign: wrapElem.querySelector('.sign'),
                resultOutput: wrapElem.querySelector('.resultOutput'),
                btns: wrapElem.querySelectorAll('.btn')
            };
    
            // 绑定事件
            each(calculatorElem.btns, function (index, elem    ) {
                    elem.onclick = function () {
                        updateSign(this.value);
                        outputResult(operate(this.title, calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                    };
            });
            
            // 遍历
            function each(array, fn) {
                for (var i = 0; i < array.length; i++) {
                    fn(i, array[i]);
                }
            }
    
            // 更新符号
            function updateSign(symbol) {
                calculatorElem.sign.innerHTML = symbol;
            }
    
            // 运算
            var operate = (function () {
                    var operation = {
                        add: function(num1, num2) {
                            return +num1 + +num2;
                        },
                    subtract: function(num1, num2) {
                            return num1 - num2;
                        },
                    multiply: function(num1, num2) {
                            return num1 * num2;
                        },
                    divide: function(num1, num2) {
                            return num1 / num2;
                       },
                       addOperation: function (name, fn) {
                            if (!operation[name]) {
                                operation[name] = fn;
                            }
                            return operation;
                        }
                };
    
                function operate(name) {
                        if (!operation[name]) throw new Error('不存在名为' + name + '的运算方法!');
                        return operation[name].apply(operation, [].slice.call(arguments, 1, arguments.length));
                }
                operate.addOperation = operation.addOperation;
    
                return operate;
            })();
    
            operate.addOperation('mod', function (num1, num2) {
                return num1 % num2;
            }).addOperation('power', function (base, power) {
                return Math.pow(base, power);
            }).addOperation('invert', function (num) {
                return 1 / num;
            });
    
            // 输出结果
            function outputResult(result) {
                calculatorElem.resultOutput.innerHTML = result;
            }
        })();
          
    </script>
    </body>
    </html>
  • 相关阅读:
    [附件解决方案]CruiseControl.NET 超冷门”BUG” 关键字:VstsHistoryParser ParseChangeSet CheckForModifications FormatException
    SQL SERVER 2008 函数大全 字符串函数
    第五章 DOM接口 DOM Interfaces
    [MSSQL]FOR XML AUTO I
    DOS CHOICE命令
    [MSSQL]NTILE另类分页有么有?!
    原生态webglDEMO,以后可能选择Three.JS来代替了,代码网上找的,参考引用
    [MSSQL]COALESCE与ISNULL函数
    【转】“无法在Web服务器上启动调试。您不具备调试此应用程序的权限,此项目的URL位于Internet区域”错误提示的解决
    【转】一个项目涉及到的50个Sql语句(整理版)
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12143674.html
Copyright © 2011-2022 走看看