JavaScript權威指南----一個JavaScript貸款計算器

廢話很少說上例子代碼:php

 

  1 <!DOCTYPE html>
  2 <html>
  3  
  4     <head>
  5         <meta charset="UTF-8">
  6         <title>JavaScript Loan Calculator</title>
  7         <style>
  8             .output{font-weight: bold;}
  9             #payment{text-decoration: underline;}
 10             #graph{border: 1px solid black;}
 11             th, td{vertical-align: top;}
 12  
 13         </style>
 14     </head>
 15  
 16     <body>
 17         <table>
 18             <tr>
 19                 <th>Enter Loan Data:</th>
 20                 <td></td>
 21                 <th>Loan Balance,Cumulative Equity,and Interest Payments</th>
 22             </tr>
 23             <tr>
 24                 <td>Amount of the loan($):</td>
 25                 <td><input id="amount" οnchange="calculate();"/></td>
 26                 <!--數量-->
 27                 <td rowspan="8"><canvas id="graph" width="400" height="250"></canvas></td>
 28                 <!--圖表-->
 29             </tr>
 30             <tr>
 31                 <td>Annual interest(%):</td>
 32                 <td><input id="apr" οnchange="calculate();" /></td>
 33                 <!--年百分利率-->
 34             </tr>
 35             <tr>
 36                 <td>Repayment period (years):</td>
 37                 <td><input id="years" οnchange="calculate();" /></td>
 38             </tr>
 39             <tr>
 40                 <td>Zipcode (to find lenders):</td>
 41                 <td><input id="zipcode" οnchange="calculate();" /></td>
 42                 <!--郵政編碼-->
 43             </tr>
 44             <tr>
 45                 <td>Approximate Payments:</td>
 46                 <td><button id="years" onclick="calculate();">Calculate</button></td>
 47                 <!--計算-->
 48             </tr>
 49             <tr>
 50                 <td>Monthly payment:</td>
 51                 <td>$<span class="output" id="payment"></span></td>
 52                 <!--付款-->
 53             </tr>
 54             <tr>
 55                 <td>Total interest:</td>
 56                 <td>$<span class="output" id="total"></span></td>
 57                 <!--所有的-->
 58             </tr>
 59             <tr>
 60                 <td>Total payment:</td>
 61                 <td>$<span class="output" id="totalinterest"></span></td>
 62                 <!--總利息-->
 63             </tr>
 64             <tr>
 65                 <th>Spinsors:</th>
 66                 <td colspan="2">
 67                     Apply for your loan with one of these fine lenders:
 68                     <div id="lenders"></div>
 69                     <!--貸款人-->
 70                 </td>
 71             </tr>
 72         </table>
 73         <script>
 74             //"use strict";
 75             function calculate(){
 76                 //查找文檔中用於輸入輸出的元素
 77                 var amount = document.getElementById("amount");
 78                 var apr = document.getElementById("apr");
 79                 var years = document.getElementById("years");
 80                 var zipcode = document.getElementById("zipcode");
 81                 var payment = document.getElementById("payment");
 82                 var total = document.getElementById("total");
 83                 var totalinterest = document.getElementById("totalinterest");
 84                 
 85                 //假如全部的輸入都是合法的,將從input中獲取輸入數據
 86                 //將百分比格式轉換成小數格式,並從年利率轉化成月利率
 87                 //將年度賠付裝換成月度賠付
 88                 var principal = parseFloat(amount.value);
 89                 var interest = parseFloat(apr.value)/100/12;
 90                 var payments = parseFloat(years.value)*12;
 91                 
 92                 //如今計算月度賠付的數據
 93                 var x =Math.pow(1+interest,payments);//Math.pow()進行冪次運算
 94                 var monthly = (principal*x*interest)/(x-1);
 95                 
 96                 //若是結果沒有超過js能表示的數字範圍,且用戶的輸入也正確
 97                 //這裏所展現的結果就是合法的
 98                 if(isFinite(monthly)){
 99                     //將數字填充到輸出字段的位置,四捨五入到小數點後兩位數字
100                     payment.innerHTML = monthly.toFixed(2);
101                     total.innerHTML = ((monthly*payments)-principal).toFixed(2);
102                     totalinterest.innerHTML=((monthly*payments)-principal).toFixed(2);
103                     
104                     //將用戶輸入的數據保存下來,這樣下次訪問時候也能取到數據
105                     save(amount.value,apr.value,years.value,zipcode.value);
106                     
107                     //找到並展現放貸人,但忽略網絡錯誤
108                     try{
109                         //捕獲這段代碼拋出的全部異常
110                         getLenders(amount.value,apr.value,years.value,zipcode.value);
111                     }
112                     //忽略這些異常
113                     catch(e){}
114                     
115                     //最後,用圖表展現貸款餘額,利息和資產收益
116                     chart(principal,interest,monthly,payments);
117                 }else{
118                     payment.innerHTML="";
119                     total.innerHTML="";
120                     totalinterest.innerHTML="";
121                     chart();
122                 }
123             }
124             
125             function save(amount,apr,years,zipcode){
126                 if(window.localStorage){//只有在瀏覽器支持的時候才支持這裏的代碼
127                     localStorage.loan_amount = amount;
128                     localStorage.loan_apr = apr;
129                     localStorage.loan_years = years;
130                     localStorage.loan_zipcode = zipcode;
131                 }
132             }
133             
134             //文檔首次加載的時候,將會嘗試還原輸入字段
135             window.οnlοad=function(){
136                 //若是瀏覽器支持本地存儲而且上次保存的值是存在的
137                 if(window.localStorage && localStorage.loan_amount){
138                     document.getElementById("amount").value = localStorage.loan_amount;
139                     document.getElementById("apr").value = localStorage.loan_apr;
140                     document.getElementById("years").value = localStorage.loan_years;
141                     document.getElementById("zipcode").value = localStorage.loan_zipcode;
142                 }
143             }
144             
145             //將用戶的輸入發送到服務器端腳本返回一個本地放貸人的鏈接列表,在這個例子中並無是如今這種查找放貸人的服務
146             //但若是該服務存在,該函數會使用它
147             function getLenders(amount,apr,years,zipcode){
148                 //若是瀏覽器不支持XMLHttpRequest對象,則退出
149                 if (!window.XMLHttpRequest)return;
150                 
151                 //找到要顯示放貸人列表的元素
152                 var ad=document.getElementById("lenders");
153                 if(!ad)return;//若是返回爲空則退出
154                 
155                 //將用戶的輸入數據進行url編碼,並做爲查詢參數附加在URL裏
156                 var url = "getLenders.php"+
157                 "?amt" + encodeURLComponent(amount)+
158                 "?apr" + encodeURLComponent(apr)+
159                 "?yrs" + encodeURLComponent(years)+
160                 "?zip" + encodeURLComponent(zipcode);
161                 
162                 //用XMLHttpRequest對象來提取返回數據
163                 var req = new XMLHttpRequest();//發送一個新的請求
164                 req.open("GET",url);//經過url發起一個http get請求
165                 req.send(null);//不帶任何正文發送這個請求
166                 
167                 //在返回數據以前,註冊一個事件處理函數,這個處理函數將會在服務器的的響應返回至客戶端的時候調用
168                 //這個異步邊城模型在客戶端js中是很是常見的
169                 req.onreadystatechange = function(){
170                     if(req.readyState == 4 && req.status == 200){
171                         //若是代碼運行到這裏,說明咱們獲得了一個合法且完整的http響應
172                         var response = req.responseText;//http響應是以字符串的形式呈現的
173                         var lenders = JSON.parse(response);//將其解析爲js數組
174                         
175                         //將數組中的放貸人對象轉換成HTML字符串的形式
176                         var list="";
177                         for(var i=0;i<lenders.length;i++){
178                             list += "<li><a href='"+ lenders[i].url +"'>"+lenders[i].name+"</a></li>"
179                         }
180                         
181                         //將數據在HTML中呈現出來
182                         ad.innerHTML = "<ul>"+list+"</ul>";
183                     }
184                 }
185                 
186             }
187             
188             //在HTML<canvas>元素中用圖表展現月度貸款餘額,利息和資產狀況    
189             //若是不傳參就清空以前的圖表
190             function chart(principal,interest,monthly,payments){
191                 var graph = document.getElementById("graph");
192                 graph.width = graph.width;//用一種巧妙的手法清除並重置畫布
193                 
194                 //若是不傳入參數,或者瀏覽器不支持畫布,則直接返回。
195                 if(arguments.length == 0 || !graph.getContext)return;
196                 
197                 //得到畫布元素『context』對象,這個對象定義了一組繪畫API
198                 var g = graph.getContext("2d");
199                 var width = graph.width,height = graph.height; 
200                 
201                 //這裏的函數的做用是將付款數字和美圓數字轉換成像素
202                 function paymentToX(n){
203                     return n*width/payments;
204                 }
205                 function amountToY(a){
206                     return height - (a*height/(monthly*payments*1.05));
207                 }
208                 
209                 //付款數據是一條從(0,0)到(payments,monthly*payments)的直線
210                 g.moveTo(paymentToX(0),amountToY(0));
211                 g.lineTo(paymentToX(payments),amountToY(monthly*payments));
212                 g.lineTo(paymentToX(payments),amountToY(0));
213                 g.closePath();
214                 g.fillStyle = "#f88";
215                 g.fill();
216                 g.font = "bold 12px sans-serif";
217                 g.fillText("Total Interest Payments",20,20);
218                 
219                 //不少資產數據並非線性的,很難將其反映到圖標中
220                 var equity = 0;
221                 g.beginPath();
222                 g.moveTo(paymentToX(0),amountToY(0));
223                 for(var p=1;p<=payments;p++){
224                     //計算出每一筆賠付的利息
225                     var thisMonthsINterest = (principal - equity)*interest;
226                     equity += (monthly -thisMonthsInterest);
227                     g.lineTo(paymentToX(p),amountToY(equity));
228                 }
229                 g.lineTo(paymentToX(payments),amountToY(0));
230                 g.closePath();
231                 g.fillStyle = "green";
232                 g.fill();
233                 g.fillText("Total Equity",20,35);
234                 
235                 //再次循環,餘額數據顯示爲黑色粗線條
236                 var bal = principal;
237                 g.beginPath();
238                 g.moveTo(paymentToX(0),amountToY(bal));
239                 for(var p=1;p<=payments;p++){
240                     var thisMonthsInterest = bal*interest;
241                     bal-=(monthly - thisMonthsInterest);
242                      g.lineTo(paymentToX(p),amountToY(bal));
243                 }
244                 
245                 g.lineWidth = 3;
246                 g.stroke();
247                 g.fillStyle ="black";
248                 g.fillText("Loan Balance",20,50);
249                 
250                 //將年度數據在X軸作標記
251                 g.textAlign = "center";
252                 var y = amountToY(0);
253                 for(var year = 1;year*12<=payments;year++){
254                     var x=paymentToX(year*12);
255                     g.fillRect(x-0.5,y-3,1,3);
256                     if(year == 1) g.fillText("Year",x,y-5);
257                     if(year %5 ==0 && year*12 !== payments)
258                     g.fillText(String(year),x,y-5);
259                 }
260                 
261                 //將賠付數額標記在右邊界
262                 g.textAlign = "right";
263                 g.textBaseline ="middle";
264                 var ticks = [monthly * payments,principal];
265                 var rightEdge = paymentToX(payments);
266                 for(var i=0;i<ticks.length;i++){
267                     var y = amountToY(ticks[i]);
268                     g.fillRect(rightEdge-3,y-0.5,3,1);
269                     g.fillText(String(ticks[i].toFixed(0)),rightEdge-5,y);
270                 }
271             }
272         </script>
273     </body>
274  
275 </html>
View Code

 

 

這邊例子有個我感受錯誤的地方:html

1 <tr>
2     <td>Approximate Payments:</td>
3     <td><button id="years" onchange="calculate();">Calculate</button></td>
4     <!--計算-->
5 </tr>
View Code

 

這裏的onchange是沒法觸發這個計算函數,須要改爲onclick函數;canvas

相關文章
相關標籤/搜索