Javascript權威指南——第一章Javascript概述

示例:javascript貸款計算器javascript

  相關技術:php

    一、如何在文檔中查找元素;css

    二、如何經過表單input元素來獲取用戶的輸入數據;html

    三、如何經過文檔元素來設置HTML內容;java

    四、如何將數據存儲在瀏覽器中;canvas

    五、如何使用腳本發起HTTP請求;瀏覽器

    六、如何利用<canvas>元素繪圖。ide

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Javascript Loan Calculator</title>
    <style type="text/css"> .output { font-weight: bold;
        } #payment { text-decoration: underline;
        } #graph { border: solid black 1px;
        } th, td { vertical-align: top;
        }
    </style>
</head>
<body>
<table>
    <tr>
        <th>Enter Loan Data:</th>
        <td></td>
        <th>Loan Balance, Cumulative Equity, and Interest Payments</th>
    </tr>
    <tr>
        <td>Amount of the loan ($):</td>
        <td><input id="amount" onchange="calculate();"/></td>
        <td rowspan="8">
            <canvas id="graph" width="400" height="250"></canvas>
        </td>
    </tr>
    <tr>
        <td>Annual interest (%):</td>
        <td><input id="apr" onchange="calculate();"/></td>
    </tr>
    <tr>
        <td>Repayment period (years):</td>
        <td><input id="years" onchange="calculate();"/></td>
    </tr>
    <tr>
        <td>Zipcode (to find lenders):</td>
        <td><input id="zipcode" onchange="calculate();"/></td>
    </tr>
    <tr>
        <th>Approximate Payments:</th>
        <td>
            <button onclick="calculate();">Calculate</button>
        </td>
    </tr>
    <tr>
        <td>Monthly payment:</td>
        <td>$<span class="output" id="payment"></span></td>
    </tr>
    <tr>
        <td>Total payment:</td>
        <td>$<span class="output" id="total"></span></td>
    </tr>
    <tr>
        <td>Total interest (%):</td>
        <td>$<span class="output" id="totalinterest"></span></td>
    </tr>
    <tr>
        <th>Sponsors:</th>
        <td colspan="2">Apply for your loan with one of these fine lenders: <div id="lenders"></div>
        </td>
    </tr>
</table>
<script type="text/javascript">
    "use strict";//若是瀏覽器支持的話,開啓ECMAScript 5的嚴格模式
 window.onload = function () { //若是瀏覽器支持本地存儲,則獲取上次保存數據
        if (window.localStorage && localStorage.loan_amount) { document.getElementById("amount").value = localStorage.loan_amount; document.getElementById("apr").value = localStorage.loan_apr; document.getElementById("years").value = localStorage.loan_years; document.getElementById("zipcode").value = localStorage.loan_zipcode; } }; function calculate() { var amount = document.getElementById("amount"); var apr = document.getElementById("apr"); var years = document.getElementById("years"); var zipcode = document.getElementById("zipcode"); var payment = document.getElementById("payment"); var total = document.getElementById("total"); var totalinterest = document.getElementById("totalinterest"); var principal = parseFloat(amount.value); var interest = parseFloat(apr.value) / 100 / 12;//百分比轉爲小數,年利率轉爲月利率
        var payments = parseFloat(years.value) * 12;//年度賠付轉爲月度賠付

        //計算月度賠付數據
        var x = Math.pow(1 + interest, payments); var monthly = (principal * x * interest) / (x - 1); if (isFinite(monthly)) { payment.innerHTML = monthly.toFixed(2); total.innerHTML = (monthly * payments).toFixed(2); totalinterest.innerHTML = ((monthly * payments) - principal).toFixed(2); //保存用戶數據
 save(amount.value, apr.value, years.value, zipcode.value); //展現本地放貸人
            try { getLenders(amount.value, apr.value, years.value, zipcode.value); } catch (e) { } chart(principal, interest, monthly, payments); } else { payment.innerHTML = ""; total.innerHTML = ""; totalinterest.innerHTML = ""; chart();//清空圖表
 } } function save(amount, apr, years, zipcode) { if (window.localStorage) { //瀏覽器支持本地存儲
 localStorage.loan_amount = amount; localStorage.loan_apr = apr; localStorage.loan_years = years; localStorage.loan_zipcode = zipcode; } } function getLenders(amount, apr, years, zipcode) { //若是瀏覽器不支持XMLHttpRequest對象,則退出
        if (!window.XMLHttpRequest) { return; } var ad = document.getElementById("lenders"); if (!ad) { return; } var url = "getLenders.php" + "?amt=" + encodeURIComponent(amount) + "&apr=" + encodeURIComponent(apr) +
                "&yrs=" + encodeURIComponent(years) + "&zip=" + encodeURIComponent(zipcode); var req = new XMLHttpRequest(); req.open("GET", url); req.send(null); req.onreadystatechange = function () { if (req.readyState == 4 && req.status == 200) { var response = req.responseText; var lenders = JSON.parse(response); var list = ""; for (var i = 0; i < lenders.length; i++) { list += "<li><a href='" + lenders[i].url + "'>" + lenders[i].name + "</a></li>"; } ad.innerHTML = "<ul>" + list + "</ul>" } }; } function chart(principal, interest, monthly, payments) { var graph = document.getElementById("graph"); graph.width = graph.width;//巧妙手法清除並重置畫布
        if (arguments.length == 0 || !graph.getContext) { //不傳入參數,或瀏覽器不支持畫布,直接返回
            return; } var g = graph.getContext('2d'); var width = graph.width; var height = graph.height; //將付款數字和美圓數據轉換爲像素
        function paymentToX(n) { return n * width / payments; } function amountToY(a) { return height - (a * height / (monthly * payments * 1.05)); } g.moveTo(paymentToX(0), amountToY(0));//從左下方開始
 g.lineTo(paymentToX(payments), amountToY(monthly * payments));//繪至右上方
 g.lineTo(paymentToX(payments), amountToY(0));//再至右下方
 g.closePath();//將結尾鏈接至開頭
 g.fillStyle = "#f88";//亮紅色
 g.fill();//填充矩形
 g.font = "bold 12px sans-serif";//定義字體
 g.fillText("Total Interest Payments", 20, 20);//將文字繪製到圖中

        var equity = 0; g.beginPath();//開始繪製新圖形
 g.moveTo(paymentToX(0), amountToY(0));//從左下方開始
        for (var p = 1; p <= payments; p++) { //賠付利息
            var thisMonthsInterest = (principal - equity) * interest; equity += (monthly - thisMonthsInterest); g.lineTo(paymentToX(p), amountToY(equity)); } g.lineTo(paymentToX(payments), amountToY(0)); g.closePath(); g.fillStyle = "green"; g.fill(); g.fillText("Total Equity", 20, 35); var bal = principal; g.beginPath(); g.moveTo(paymentToX(0), amountToY(bal)); for (var p = 1; p <= payments; p++) { var thisMonthsInterest = bal * interest; bal -= (monthly - thisMonthsInterest); g.lineTo(paymentToX(p), amountToY(bal)); } g.lineWidth = 3; g.stroke(); g.fillStyle = 'black'; g.fillText("Loan Balance", 20, 50); //X軸
 g.textAlign = "center"; var y = amountToY(0); for (var year = 1; year * 12 <= payments; year++) { var x = paymentToX(year * 12); g.fillRect(x - 0.5, y - 3, 1, 3); if (year == 1) { g.fillText("Year", x, y - 5); } if (year % 5 == 0 && year * 12 !== payments) { g.fillText(String(year), x, y - 5); } } //賠付數額標記在有邊界
 g.textAlign = 'right'; g.textBaseline = 'middle'; var ticks = [monthly * payments, principal]; var rightEdge = paymentToX(payments); for (var i = 0; i < ticks.length; i++) { var y = amountToY(ticks[i]); g.fillRect(rightEdge - 3, y - 0.5, 3, 1); g.fillText(String(ticks[i].toFixed(0)), rightEdge - 5, y); } } </script>
</body>
</html>
貸款計算器
相關文章
相關標籤/搜索