当我在控制台中调用btn.onClick时,我收到此错误: {Uncaught TypeError:无法设置属性'onClick'为null}
此处的代码:
=============== HTML ==================
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<h3 class="billboard">Wacky Expressions Assignment</h3>
<p><b>Cost of Shoe Strings</b>:<input type="text" id="inCost"/></p>
<p><b>Down Payment</b>:<input type="text" id="inDown"/></p>
<p><b>APR (Intrest)</b>:<input type="text" id="inAPR"/></p>
<p><b>Term (How long)</b>:<input type="text" id="inTime"/></p>
<p><button id="btnCalculate">Calculate Payments</button></p>
<p><b>Monthly Payments</b>:<span id="outMonthly"/></p>
</div>
<script language="JavaScript" src="js/script.js" type="text/javascript"></script>
</body>
</html>
=============== JS ==================
//The Formula: c = (r * p) / (1 - (Math.pow((1 + r), (-n))));
//@param p float Amount borrowed
//@param r interest, as a percentage
//@param n term in years
function calculateMortgage(p, r, n ) { //setting function for mortgage calculator
//converting this percentage to a decimal
var r = percentToDecimal(r);
//convert years to months
n = yearsToMonths(n); //parameters set for n = conversion of years to months
//convert data with formula for obtaining monthly payments
var pmt = (r * p) / (1 - (Math.pow((1 + r), (-n))));
return parseFloat(pmt.toFixed(2));
return monthlyPayments; //returning to variabale monthly
}
function percentToDecimal(percent) { /
return (percent/12) / 100; //assigning calculation for conversion of input
}
function postPayments(payment) {
var htmlEl = document.getElementById("outMonthly");
htmlEl.innerText = "$" + payment;
}
function yearsToMonths(year) { //function setup for converting year to months
return year * 12; //assigning calculation for years to months
}
var btn = document.getElementById("btnCalculate");
btn.onclick = function calculateMortgage( p, r , n) {
var cost = document.getElementById("inCost").value; //declaring variables for cost
var downPayment = document.getElementById("inDown").value;
var interest = document.getElementById("inAPR").value; //declaring variable for intrest
var term = document.getElementById("inTime").value; //declaring variable for term
var amountBorrowed = cost - downPayment; //declaring varibales for amount borrowed
var pmt = calculateMortgage(amountBorrowed, interest, term);
postPayments(pmt);
}
//console.log(cost, downPayment, interest, term);
//console.log("R", p); //call out log for para p
//console.log("R", r); //call out log for para r
//console.log("R", n); //call out log for para n
答案 0 :(得分:1)
从上到下加载HTML文档。该脚本在加载DOM之前执行,因此在脚本执行时,页面上不存在btnCalculate
。
如果您将脚本放在页面底部,这可以解决您的问题。
答案 1 :(得分:1)
您的脚本在浏览器完成页面解析之前正在执行,因此#btnCalculate
元素尚不存在,因此它为空。
解决问题的最快方法是将脚本标记移动到正文标记的末尾,将其放在</body>
之前。
另一个注意事项:onClick
不是正确的属性,而必须是onclick
,全部为小写。