js函数没有返回onclick

时间:2017-06-19 21:37:24

标签: javascript function onclick jsfiddle

我创建了一个无法通过onclick返回的函数。

我确信这很简单,我很遗憾。

HTML:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="schedule.js"></script>
</head>
<body>

     <input type="button" onclick="computeSchedule();" value="Submit" /><br>
     <p id="scheduleOutput"></p>

</body>
</html>

JS:

function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;

for (var i=0; i<=number_of_payments; i++) {
    var interest = remaining * (interest_rate/100/payments_per_year);
    var principle = (payment-interest);
    var row = [i, principle>0?principle:0, interest>0?interest:0, remaining>0?remaining:0];
    schedule.push(row);
    remaining -= principle
}

return schedule;
}

var list = JSON.stringify(computeSchedule(100000, 0.005, 12, 15, 843.86), 0, 4)

document.getElementById('scheduleOutput').innerHTML = list;

我可以让函数在jsFiddle onload中自动返回,但是当我将js设置更改为"no wrap - in head"时,它不起作用。我假设发生了什么事情,当我试图在jsFiddle之外运行时也会发生这种情况?

2 个答案:

答案 0 :(得分:1)

在身体内容准备好之前,您将运行sripts。这就是为什么document.getElementById似乎不起作用的原因,因为此时此类元素不存在。

尝试将您的代码包装在简单的内容加载中#34;监听器确保它将在所有元素准备好后运行:

document.addEventListener('DOMContentLoaded', function() {
    function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
        var schedule = [];
        var remaining = loan_amount;
        var number_of_payments = payments_per_year * years;

        for (var i=0; i<=number_of_payments; i++) {
            var interest = remaining * (interest_rate/100/payments_per_year);
            var principle = (payment-interest);
            var row = [i, principle>0?principle:0, interest>0?interest:0, remaining>0?remaining:0];
            schedule.push(row);
            remaining -= principle
        }

        return schedule;
    }

    var list = JSON.stringify(computeSchedule(100000, 0.005, 12, 15, 843.86), 0, 4)

    document.getElementById('scheduleOutput').innerHTML = list;
});

是的,你的 onclick 现在没有数据传递给该函数。所以,你还需要将params传递给它,一切都应该正常工作。

答案 1 :(得分:0)

当您单击按钮时,函数computeSchedule()将触发,但没有值传递给它。如果你把值放在html行的参数上,我会打赌它会起作用。

<input type="button" onclick="computeSchedule(100000, 0.005, 12, 15, 843.86);" value="Submit" />