2014-01-17 2 views
0

내가 콘솔에서 btn.onClick을 호출이 오류 받고 있어요의 설정할 수 없습니다 재산 '온 클릭'catch되지 않은 유형의 오류 : 널 (null)

코드를 {catch되지 않는 형식 오류가 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 

답변

1

HTML 문서가 위에서 아래로로드됩니다. DOM이로드되기 전에 스크립트가 실행 중이므로 스크립트가 실행될 때 페이지에 btnCalculate이 없습니다.

스크립트를 페이지 맨 아래에두면 문제가 해결됩니다.

+0

실례합니다. 여기에 멍청한 놈입니다. 학교에서 처음으로 이것을 배우십시오. 조심스럽게 "나는 넣어야한다 : jt의 세부 정보를 htl 페이지의 맨 아래에 넣는다. ... – simpleWebGuy

+0

도움을 주셔서 감사합니다. 코드를 수정하는 데 도움이되었습니다. – simpleWebGuy

1

페이지가 브라우저에서 구문 분석되기 전에 스크립트가 실행되고 있으므로 #btnCalculate 요소가 아직 존재하지 않으므로 null입니다.

가장 빠른 방법은 body 태그의 끝까지 스크립트 태그를 이동하여 </body> 바로 앞에 두는 것입니다.

다른 메모 : onClick은 올바른 속성이 아니며 대신 모두 onclick이어야하며 모두 소문자 여야합니다.

+0

내 코드를 수정 해 주셔서 감사합니다. 귀하의 마크 업 내의 기능들입니다. 감사합니다. 해피 프라이데이 – simpleWebGuy

+0

도움이 되었으니 기쁩니다! 내 대답의 왼쪽에있는 체크 표시를 클릭하면 "올바른"대답으로 선택할 수 있습니다. – mwcz

관련 문제