開發者實現的法律費用計算器在切換「年利率/月利率/日利率」單選框時,計算結果未隨單位變化。核心問題在於三個計算函數 `Costcalculator`、`Costcalculator1`、`Costcalculator2` 邏輯高度重複,僅除數不同(1、12、365),且事件綁定方式導致函數未正確觸發。
onclick="Costcalculator1" → 應為 onclick="Costcalculator1(parseFloat(...), parseFloat(...))"// 統一計算入口
function calculate(principal, rate, periodType) {
const periods = { 'year': 1, 'month': 12, 'day': 365 };
const divisor = periods[periodType] || 1;
// ... 核心費用計算邏輯(只寫一次)
// 最後統一除以 divisor
return { full: total / divisor, half: halfTotal / divisor, ... };
}
// 事件綁定
$('input[name="standard1"]').on('change', function() {
const type = $(this).attr('id'); // '1-6'年, '1-4'月, '1-5'日
const periodMap = { '1-6': 'year', '1-4': 'month', '1-5': 'day' };
const result = calculate(
parseFloat($('#input').val()) || 0,
parseFloat($('#input1').val()) || 0,
periodMap[type]
);
renderResult(result);
});
// 輸入框變化觸發重算
$('#input, #input1').on('input', () => {
$('input[name="standard1"]:checked').trigger('change');
});
完整 HTML/JS 代碼較長,建議參考重構思路自行實現,或使用 Vue/React 等框架進一步組件化。