2012-05-08 38 views
0

我是JavaScript新手,試圖瞭解更多關於它可以做什麼以及如何使用它的知識。在innerHTML中返回多個結果

是否可以返回多個結果作爲計算的結果?

我正在爲班級項目計算器。我想它做的是我的頁面上的返回3個值:

Interest rate

total amount borrowedmonthly 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; 

} 

如果任何人都可以在正確的方向指向我,那就太好了!

回答

1

您可以創建具有多個自定義字段的變量並在函數之間傳遞它們。所以,你的功能應該是這樣的:

function main() 
{ 
    ... 

    displayResult = calcLoan(userInput1,userInput2); 
    document.getElementById("Result1").innerHTML = displayResult.interest; 
    document.getElementById("Result2").innerHTML = displayResult.totalLoan; 
    document.getElementById("Result3").innerHTML = displayResult.monthly; 
} 

function calcLoan(userInput1,userInput2) 
{ 
    ... 

    alert("Interest Rate = " + interest + "%" +" "+"Total Loan amount = " + "£"+ totalLoan +" "+ "Your monthly repayment is = " + " " + "£"+ monthly); 

    var result; 
    result.interest = interest; 
    result.totalLoan = totalLoan; 
    result.monthly = monthly; 

    return result; 
} 

而且不要忘了添加有ID的結果1,結果2和Result3 div元素。

<div id="Result1"></div> 
<div id="Result2"></div> 
<div id="Result3"></div> 
+0

謝謝,我會給它一個並讓你知道 – user1361276

+0

我試過這種方法。錯誤控制檯提供錯誤「result id undefined」引用var result; result.interest = interest; result.totalLoan = totalLoan; result.monthly = monthly;' – user1361276

+0

OK。將'var result;'更改爲'var result = [];'。現在它應該工作。 – mostar