首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 簡易貸款計算器:修復重複綁定事件與計算邏輯錯誤

     編輯:程式設計疑難解答

原代碼問題分析

  1. 重複綁定 click 事件:HTML `
  2. 計算公式錯誤:`var s = p1 / p2 * s + p1` 中變量 `s` 未定義(自我引用),應為利率 `p3`。
  3. $(document).ready 放在函數內:每次點擊才綁定,邏輯顛倒。
  4. 未做輸入驗證:非數字輸入導致 NaN。

修正後完整代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>貸款計算器</title>
    <style>
        body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; }
        .form-group { margin-bottom: 1rem; }
        label { display: inline-block; width: 80px; text-align: right; margin-right: 0.5rem; }
        input { padding: 0.4rem; width: 200px; }
        button { padding: 0.5rem 1.5rem; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
        #result { margin-top: 1rem; font-weight: bold; color: #28a745; }
    </style>
</head>
<body>
    <h2>貸款本息計算</h2>
    <div class="form-group">
        <label>貸款總額:</label>
        <input type="number" id="principal" step="0.01" placeholder="如 100000">
    </div>
    <div class="form-group">
        <label>期數(月):</label>
        <input type="number" id="periods" min="1" placeholder="如 12">
    </div>
    <div class="form-group">
        <label>月利率(%):</label>
        <input type="number" id="rate" step="0.001" placeholder="如 0.5 表示 0.5%">
    </div>
    <button onclick="calculate()">計算月供</button>
    <div id="result"></div>

    <script>
        function calculate() {
            const p = parseFloat(document.getElementById('principal').value);
            const n = parseInt(document.getElementById('periods').value, 10);
            const r = parseFloat(document.getElementById('rate').value) / 100; // 轉小數

            if (isNaN(p) || isNaN(n) || isNaN(r) || n <= 0 || r < 0) {
                document.getElementById('result').textContent = '請填寫有效數字';
                return;
            }

            // 等額本息公式:月供 = P * r * (1+r)^n / ((1+r)^n - 1)
            const monthly = p * r * Math.pow(1 + r, n) / (Math.pow(1 + r, n) - 1);
            const total = monthly * n;
            const interest = total - p;

            document.getElementById('result').innerHTML = 
                `月供: ${monthly.toFixed(2)} 元
` + `總還款: ${total.toFixed(2)} 元
` + `總利息: ${interest.toFixed(2)} 元`; } </script> </body> </html>

關鍵修正點

問題修正
雙重綁定移除 JS 內綁定,保留 HTML `onclick="calculate()"`
公式錯誤使用標準等額本息公式,利率變量改為 `r`
無驗證檢查 NaN、期數>0、利率>=0
用戶體驗添加 CSS 美化,結果分項顯示

進階擴展建議

  • 支持等額本金模式:月供遞減,總利息更少。
  • 添加還款明細表導出 CSV/Excel。
  • 引入 Intl.NumberFormat 格式化金額(千分位、貨幣符號)。
  • 封裝為 ES Module / Vue/React 組件復用。

總結

JS 事件綁定二選一:要么 HTML 內聯 `onclick`,要么 JS `addEventListener`,切勿混用。計算邏輯務必用標準金融公式,並做好輸入驗證與用戶反饋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved