我正在尝试制作一个简单的信用卡还款计算器脚本,但似乎遇到了“while”循环的问题。它适用于低数字,但是当您开始输入较大的数字时,它会冻结浏览器,然后您必须退出并重新打开。
这是我拥有的 JavaScript (jQuery):
$('#calculate').click(function()
{
var currentBalance = parseFloat($('#current_balance').val().substring(1)); // substring so it doesnt grab the £ sign
var interestRate = parseFloat($('#interest_rate').val());
var interestType = $('#interest_type').val();
var monthlyPayment = parseFloat($('#monthly_payment').val().substring(1));
var totalInterest = 0;
var interest = 0;
var months = 0;
while(currentBalance > 0) // while there is still a balance on the card run the following
{
interest = (currentBalance/100)*interestRate; // find interest amount for this month
currentBalance = currentBalance+interest; // add the interest to the balance
currentBalance = currentBalance-monthlyPayment; // subtract monthly payment from balance
totalInterest = totalInterest+interest; // total amount of interest paid
months++;
}
var years = parseInt(months / 12);
var remainingMonths = months % 12;
totalInterest = Math.round(totalInterest);
$('#clear_balance').val(years+' years and '+remainingMonths+' months');
$('#interest_paid').val('£'+totalInterest);
});
这是我的 HTML:
<table id="card-info">
<tbody>
<tr>
<td><label for="current_balance">Current balance</label></td>
<td><input type="text" id="current_balance" /></td>
</tr>
<tr>
<td><label for="interest_rate">Interest rate</label></td>
<td>
<input type="text" id="interest_rate" />
<select id="interest_type">
<option value="monthly">Monthly</option>
<option value="yearly">Yearly</option>
</select>
</td>
</tr>
<tr>
<td><label for="monthly_payment">Monthly payment</label></td>
<td><input type="text" id="monthly_payment" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2"><button id="calculate">Calculate</button></td>
</tr>
</tbody>
</table>
</div>
<div id="results">
<table id="results-info">
<tbody>
<tr>
<td>
<label for="clear_balance">Time to clear balance</label><br />
<input type="text" id="clear_balance" />
</td>
<td>
<label for="interest_paid">Total interest paid</label><br />
<input type="text" id="interest_paid" />
</td>
</tr>
</tbody>
</table>
有什么我做错了吗?