JS做一個四則運算計算器


用JS做一個簡單的網頁計算器如上圖所示,只進行簡單的加減乘除運算

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>計數器</title>
</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();">
    <script>
    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>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM