js之簡單加法計算器


在頁面中做了一個簡單的加法計算器,實現實時計算輸入的數值:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
<script type="text/javascript">

$(document).ready(
    function(){
        //定義一個通用的合計函數
        function compute(arrName,resultName){
            var result = 0 ; 
            for(var i = 0 ; i < arrName.length; i++){
                result +=Number($('input[name='+arrName[i]+']').val() );
            }
            $('input[name='+resultName+']').val(result);
        }
        
        //定義輸入    
        var arrName = ['num1','num2'];
        
        //存放計算結果
        var resultName = 'result';
        
        //將compute綁定到每一個輸入框的blur事件
        for(var i = 0 ; i < arrName.length; i++){
          $("input[name="+arrName[i]+"]").on('keydown',{arrName:arrName,resultName:resultName},function(e){
                compute(arrName,resultName);
            //    debugger;
          }); 
        }
        
                  
    }    
);
</script>
</head>
<body>
    <center>
        <input type="text" name="num1" value="15" style = 'width:34px;height:34px' />
        +
        <input type="text" name="num2" value="6" style='width:34px;height:34px'/>
        =<input type="text" name="result" value="" readonly="true" style='background-color:lightgray;width:34px;height:34px'/>

    </center>
</body>
</html>

 


免責聲明!

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



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