我是JavaScript新手,試圖瞭解更多關於它可以做什麼以及如何使用它的知識。在innerHTML中返回多個結果
是否可以返回多個結果作爲計算的結果?
我正在爲班級項目計算器。我想它做的是我的頁面上的返回3個值:
Interest rate
total amount borrowed
和 monthly repayment
到目前爲止,我已經成功地得到它在一個div在頁面上顯示每月還款,但我希望能夠通過一次計算顯示頁面上的所有3個。
這可能嗎?
以下是我想出迄今: HTML: <p><input type="button" onclick="main();" value="Calculate"></p>
的JavaScript:
function main()
{
var userInput1 = 0;
var userInput2 = 0;
var displayResult;
userInput1 = document.getElementById("loan_amount").value;
userInput1 = parseFloat(userInput1);
userInput2 = document.getElementById("loan_term").value;
userInput2 = parseFloat(userInput2);
displayResult = calcLoan(userInput1,userInput2);
document.getElementById("Result1").innerHTML=displayResult;
}
function calcLoan(userInput1,userInput2)
{
var interest =0;
if (userInput1 <1000)
{
alert("Please enter a value above £1000")
}
else if (userInput1 <= 10000)
{
interest = 4.25 + 5.5;
}
else if (userInput1 <= 50000)
{
interest = 4.25 + 4.5;
}
else if (userInput1 <= 100000)
{
interest = 4.25 + 3.5;
}
else
{
interest = 4.25 + 2.5;
}
var totalLoan = 0;
totalLoan = userInput1 +(userInput1*(interest/100))*userInput2;
var monthlyRepayment = 0;
var monthly;
monthlyRepayment = totalLoan/(userInput2*12);
monthly=monthlyRepayment.toFixed(2);
alert("Interest Rate = " + interest + "%" +" "+"Total Loan amount = " + "£"+ totalLoan +" "+ "Your monthly repayment is = " + " " + "£"+ monthly);
return monthly;
}
如果任何人都可以在正確的方向指向我,那就太好了!
謝謝,我會給它一個並讓你知道 – user1361276
我試過這種方法。錯誤控制檯提供錯誤「result id undefined」引用var result; result.interest = interest; result.totalLoan = totalLoan; result.monthly = monthly;' – user1361276
OK。將'var result;'更改爲'var result = [];'。現在它應該工作。 – mostar