通过这个例子思考下列问题
• 1 怎么得到文档中的元素?
答:使用document.getElementById("ID")
• 怎么的到用户的输入,从输入元素里面.
答:通过元素的.value获得
• 怎么设置文档中某一个元素的内容
答:通过 elment.innerHTML ="";
• 怎么存储数据在浏览器下.
答:用window.localStorage,擦这个html5才支持吧
• 怎么用脚本请求页面.
答:用XMLHttpRequest对象。
• 如何用<canvas> 元素画图.
答:var g = canvas.getContext("2d");
g.beginPath(),moveto,endPath(); g.stroke(); g.fillRect(); g.fillText()等。
例子:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>JavaScript Loan Calculator</title> 5 <style> /* This is a CSS style sheet: it adds style to the program output */ 6 .output { font-weight: bold; } /* Calculated values in bold */ 7 #payment { text-decoration: underline; } /* For element with id="payment" */ 8 #graph { border: solid black 1px; } /* Chart has a simple border */ 9 th, td { vertical-align: top; } /* Don't center table cells */ 10 </style> 11 </head> 12 <body> 13 <!-- 14 This is an HTML table with <input> elements that allow the user to enter data 15 and <span> elements in which the program can display its results. 16 These elements have ids like "interest" and "years". These ids are used 17 in the JavaScript code that follows the table. Note that some of the input 18 elements define "onchange" or "onclick" event handlers. These specify strings 19 of JavaScript code to be executed when the user enters data or clicks. 20 --> 21 <table> 22 <tr><th>Enter Loan Data:</th> 23 <td></td> 24 <th>Loan Balance, Cumulative Equity, and Interest Payments</th></tr> 25 <tr><td>Amount of the loan ($):</td> 26 <td><input id="amount" onchange="calculate();"></td> 27 <td rowspan=8> 28 <canvas id="graph" width="400" height="250"></canvas></td></tr> 29 <tr><td>Annual interest (%):</td> 30 <td><input id="apr" onchange="calculate();"></td></tr> 31 <tr><td>Repayment period (years):</td> 32 <td><input id="years" onchange="calculate();"></td> 33 <tr><td>Zipcode (to find lenders):</td> 34 <td><input id="zipcode" onchange="calculate();"></td> 35 <tr><th>Approximate Payments:</th> 36 <td><button onclick="calculate();">Calculate</button></td></tr> 37 <tr><td>Monthly payment:</td> 38 <td>$<span class="output" id="payment"></span></td></tr> 39 <tr><td>Total payment:</td> 40 <td>$<span class="output" id="total"></span></td></tr> 41 1.2 Client-Side JavaScript | 13 <tr><td>Total interest:</td> 42 <td>$<span class="output" id="totalinterest"></span></td></tr> 43 <tr><th>Sponsors:</th><td colspan=2> 44 Apply for your loan with one of these fine lenders: 45 <div id="lenders"></div></td></tr> 46 </table> 47 <!-- The rest of this example is JavaScript code in the <script> tag below --> 48 <!-- Normally, this script would go in the document <head> above but it --> 49 <!-- is easier to understand here, after you've seen its HTML context. --> 50 <script> 51 "use strict"; // Use ECMAScript 5 strict mode in browsers that support it 52 /* 53 * This script defines the calculate() function called by the event handlers 54 * in HTML above. The function reads values from <input> elements, calculates 55 * loan payment information, displays the results in <span> elements. It also 56 * saves the user's data, displays links to lenders, and draws a chart. 57 */ 58 function calculate() { 59 // Look up the input and output elements in the document 60 var amount = document.getElementById("amount"); 61 var apr = document.getElementById("apr"); 62 var years = document.getElementById("years"); 63 var zipcode = document.getElementById("zipcode"); 64 var payment = document.getElementById("payment"); 65 var total = document.getElementById("total"); 66 var totalinterest = document.getElementById("totalinterest"); 67 68 // Get the user's input from the input elements. Assume it is all valid. 69 // Convert interest from a percentage to a decimal, and convert from 70 // an annual rate to a monthly rate. Convert payment period in years 71 // to the number of monthly payments. 72 var principal = parseFloat(amount.value); 73 var interest = parseFloat(apr.value) / 100 / 12; 74 var payments = parseFloat(years.value) * 12; 75 // Now compute the monthly payment figure. 76 var x = Math.pow(1 + interest, payments); // Math.pow() computes powers 77 var monthly = (principal*x*interest)/(x-1); 78 // If the result is a finite number, the user's input was good and 79 // we have meaningful results to display 80 if (isFinite(monthly)) { 81 // Fill in the output fields, rounding to 2 decimal places 82 payment.innerHTML = monthly.toFixed(2); 83 total.innerHTML = (monthly * payments).toFixed(2); 84 totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2); 85 // Save the user's input so we can restore it the next time they visit 86 save(amount.value, apr.value, years.value, zipcode.value); 87 88 // Advertise: find and display local lenders, but ignore network errors 89 try { // Catch any errors that occur within these curly braces 90 getLenders(amount.value, apr.value, years.value, zipcode.value); 91 } 92 14 | Chapter 1: Introduction to JavaScript catch(e) { /* And ignore those errors */ } 93 // Finally, chart loan balance, and interest and equity payments 94 chart(principal, interest, monthly, payments); 95 } 96 else { 97 // Result was Not-a-Number or infinite, which means the input was 98 // incomplete or invalid. Clear any previously displayed output. 99 payment.innerHTML = ""; // Erase the content of these elements 100 total.innerHTML = "" 101 totalinterest.innerHTML = ""; 102 chart(); // With no arguments, clears the chart 103 } 104 } 105 // Save the user's input as properties of the localStorage object. Those 106 // properties will still be there when the user visits in the future 107 // This storage feature will not work in some browsers (Firefox, e.g.) if you 108 // run the example from a local file:// URL. It does work over HTTP, however. 109 function save(amount, apr, years, zipcode) { 110 if (window.localStorage) { // Only do this if the browser supports it 111 localStorage.loan_amount = amount; 112 localStorage.loan_apr = apr; 113 localStorage.loan_years = years; 114 localStorage.loan_zipcode = zipcode; 115 } 116 } 117 // Automatically attempt to restore input fields when the document first loads. 118 window.onload = function() { 119 // If the browser supports localStorage and we have some stored data 120 if (window.localStorage && localStorage.loan_amount) { 121 document.getElementById("amount").value = localStorage.loan_amount; 122 document.getElementById("apr").value = localStorage.loan_apr; 123 document.getElementById("years").value = localStorage.loan_years; 124 document.getElementById("zipcode").value = localStorage.loan_zipcode; 125 } 126 }; 127 // Pass the user's input to a server-side script which can (in theory) return 128 // a list of links to local lenders interested in making loans. This example 129 // does not actually include a working implementation of such a lender-finding 130 // service. But if the service existed, this function would work with it. 131 function getLenders(amount, apr, years, zipcode) { 132 // If the browser does not support the XMLHttpRequest object, do nothing 133 if (!window.XMLHttpRequest) return; 134 // Find the element to display the list of lenders in 135 var ad = document.getElementById("lenders"); 136 if (!ad) return; // Quit if no spot for output 137 1.2 Client-Side JavaScript | 15 // Encode the user's input as query parameters in a URL 138 var url = "getLenders.php" + // Service url plus 139 "?amt=" + encodeURIComponent(amount) + // user data in query string 140 "&apr=" + encodeURIComponent(apr) + 141 "&yrs=" + encodeURIComponent(years) + 142 "&zip=" + encodeURIComponent(zipcode); 143 // Fetch the contents of that URL using the XMLHttpRequest object 144 var req = new XMLHttpRequest(); // Begin a new request 145 req.open("GET", url); // An HTTP GET request for the url 146 req.send(null); // Send the request with no body 147 // Before returning, register an event handler function that will be called 148 // at some later time when the HTTP server's response arrives. This kind of 149 // asynchronous programming is very common in client-side JavaScript. 150 req.onreadystatechange = function() { 151 if (req.readyState == 4 && req.status == 200) { 152 // If we get here, we got a complete valid HTTP response 153 var response = req.responseText; // HTTP response as a string 154 var lenders = JSON.parse(response); // Parse it to a JS array 155 // Convert the array of lender objects to a string of HTML 156 var list = ""; 157 for(var i = 0; i < lenders.length; i++) { 158 list += "<li><a href='" + lenders[i].url + "'>" + 159 lenders[i].name + "</a>"; 160 } 161 // Display the HTML in the element from above. 162 ad.innerHTML = "<ul>" + list + "</ul>"; 163 } 164 } 165 } 166 // Chart monthly loan balance, interest and equity in an HTML <canvas> element. 167 // If called with no arguments then just erase any previously drawn chart. 168 function chart(principal, interest, monthly, payments) { 169 var graph = document.getElementById("graph"); // Get the <canvas> tag 170 graph.width = graph.width; // Magic to clear and reset the canvas element 171 // If we're called with no arguments, or if this browser does not support 172 // graphics in a <canvas> element, then just return now. 173 if (arguments.length == 0 || !graph.getContext) return; 174 // Get the "context" object for the <canvas> that defines the drawing API 175 var g = graph.getContext("2d"); // All drawing is done with this object 176 var width = graph.width, height = graph.height; // Get canvas size 177 // These functions convert payment numbers and dollar amounts to pixels 178 function paymentToX(n) { return n * width/payments; } 179 function amountToY(a) { return height-(a * height/(monthly*payments*1.05));} 180 // Payments are a straight line from (0,0) to (payments, monthly*payments) 181 g.moveTo(paymentToX(0), amountToY(0)); // Start at lower left 182 g.lineTo(paymentToX(payments), // Draw to upper right 183 amountToY(monthly*payments)); 184 16 | Chapter 1: Introduction to JavaScript g.lineTo(paymentToX(payments), amountToY(0)); // Down to lower right 185 g.closePath(); // And back to start 186 g.fillStyle = "#f88"; // Light red 187 g.fill(); // Fill the triangle 188 g.font = "bold 12px sans-serif"; // Define a font 189 g.fillText("Total Interest Payments", 20,20); // Draw text in legend 190 // Cumulative equity is non-linear and trickier to chart 191 var equity = 0; 192 g.beginPath(); // Begin a new shape 193 g.moveTo(paymentToX(0), amountToY(0)); // starting at lower-left 194 for(var p = 1; p <= payments; p++) { 195 // For each payment, figure out how much is interest 196 var thisMonthsInterest = (principal-equity)*interest; 197 equity += (monthly - thisMonthsInterest); // The rest goes to equity 198 g.lineTo(paymentToX(p),amountToY(equity)); // Line to this point 199 } 200 g.lineTo(paymentToX(payments), amountToY(0)); // Line back to X axis 201 g.closePath(); // And back to start point 202 g.fillStyle = "green"; // Now use green paint 203 g.fill(); // And fill area under curve 204 g.fillText("Total Equity", 20,35); // Label it in green 205 // Loop again, as above, but chart loan balance as a thick black line 206 var bal = principal; 207 g.beginPath(); 208 g.moveTo(paymentToX(0),amountToY(bal)); 209 for(var p = 1; p <= payments; p++) { 210 var thisMonthsInterest = bal*interest; 211 bal -= (monthly - thisMonthsInterest); // The rest goes to equity 212 g.lineTo(paymentToX(p),amountToY(bal)); // Draw line to this point 213 } 214 g.lineWidth = 3; // Use a thick line 215 g.stroke(); // Draw the balance curve 216 g.fillStyle = "black"; // Switch to black text 217 g.fillText("Loan Balance", 20,50); // Legend entry 218 // Now make yearly tick marks and year numbers on X axis 219 g.textAlign="center"; // Center text over ticks 220 var y = amountToY(0); // Y coordinate of X axis 221 for(var year=1; year*12 <= payments; year++) { // For each year 222 var x = paymentToX(year*12); // Compute tick position 223 g.fillRect(x-0.5,y-3,1,3); // Draw the tick 224 if (year == 1) g.fillText("Year", x, y-5); // Label the axis 225 if (year % 5 == 0 && year*12 !== payments) // Number every 5 years 226 g.fillText(String(year), x, y-5); 227 } 228 // Mark payment amounts along the right edge 229 g.textAlign = "right"; // Right-justify text 230 g.textBaseline = "middle"; // Center it vertically 231 var ticks = [monthly*payments, principal]; // The two points we'll mark 232 var rightEdge = paymentToX(payments); // X coordinate of Y axis 233 for(var i = 0; i < ticks.length; i++) { // For each of the 2 points 234 var y = amountToY(ticks[i]); // Compute Y position of tick 235 1.2 Client-Side JavaScript | 17 g.fillRect(rightEdge-3, y-0.5, 3,1); // Draw the tick mark 236 g.fillText(String(ticks[i].toFixed(0)), // And label it. 237 rightEdge-5, y); 238 } 239 } 240 </script> 241 </body> 242 </html>