在 innerHTML 中返回多个结果

Returning multiple results in innerHTML

本文关键字:结果 返回 innerHTML      更新时间:2023-09-26

我是JavaScript的新手,并试图更多地了解它可以做什么以及如何使用它。

是否可以返回多个结果作为计算结果?

我正在为一个班级项目开发计算器。我希望它做的是在我的页面上返回 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; 
}

如果有人能指出我正确的方向,那就太好了!

您可以创建具有多个自定义字段的变量,并在函数之间传递它们。因此,您的函数应如下所示:

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为Result1,Result2和Result3的div元素。

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

尝试一些JavaScript OOP。一个函数可以很容易地返回多个值。有几种方法可以做到这一点。尝试阅读以下内容:http://killdream.github.com/blog/2011/10/understanding-javascript-oop/和以下内容:http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/