<!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 美化,結果分項顯示 |
Intl.NumberFormat 格式化金額(千分位、貨幣符號)。JS 事件綁定二選一:要么 HTML 內聯 `onclick`,要么 JS `addEventListener`,切勿混用。計算邏輯務必用標準金融公式,並做好輸入驗證與用戶反饋。