Maison > interface Web > js tutoriel > le corps du texte

Le script JavaScript implémente la fonction de calcul de prêt (code complet)

php是最好的语言
Libérer: 2018-08-04 09:47:29
original
3631 Les gens l'ont consulté

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>javascript学习</title>
        <style>
            .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>
                <td>
                    Approximate Payments:
                </td>
                <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:
                    <p id="lenders">
                    </p>
                </td>
            </tr>
        </table>
        <script>
        &#39;use strict&#39;;
        function calculate () {
            var amount = document.getElementById(&#39;amount&#39;);
            var apr = document.getElementById(&#39;apr&#39;);
            var years = document.getElementById(&#39;years&#39;);
            var zipcode = document.getElementById(&#39;zipcode&#39;);
            var payment = document.getElementById(&#39;payment&#39;);
            var total = document.getElementById(&#39;total&#39;);
            var totalinterest = document.getElementById(&#39;totalinterest&#39;);
            // 将百分比格式转化为小数格式,并从年利率转化为月利率  将年度赔付转化为月度赔付
            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);
            // 如果没超过js可以表示的数字范围,并且用户输入正确
            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 = &#39;&#39;;
                total.innerHTML = &#39;&#39;;
                totalinterest.innerHTML = &#39;&#39;;
                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 = amount;
            }
        }
        // 文档首次加载时,将会尝试还原输入字段
        window.onload = function () {
            if (window.localStorage && localStorage.loan_amount) {
                document.getElementById(&#39;amount&#39;).value = localStorage.loan_amount;
                document.getElementById(&#39;apr&#39;).value = localStorage.loan_apr;
                document.getElementById(&#39;years&#39;).value = localStorage.loan_years;
                document.getElementById(&#39;zipcode&#39;).value = localStorage.loan_zipcode;

            }
        };
        // 将用户输入的内容发送给服务器脚本上
        function getLenders(amount, apr, years, zipcode) {
            if (!window.XMLHttpRequest)
                return;
            var ad = document.getElementById(&#39;lenders&#39;);
            if (!ad)
                return;
            // 用户输入的数据进行url编码,并作为查询参数附加在url中
            var url = &#39;getLenders.php&#39; + &#39;&?amt=&#39; + encodeURIComponent(amount) + &#39;&?apr=&#39; + encodeURIComponent(apr) + &#39;&?yrs=&#39; + encodeURIComponent(years) + &#39;&zip=&#39; + encodeURIComponent(zipcode);
            // 通过xml对象提取返回数据
            var req = new XMLHttpRequest();
            req.open(&#39;GET&#39;, url);
            req.send(null);
            // 在返回数据之前,注册一个事件处理函数,这个处理函数在服务器响应返回客户端的时候调用
            req.onreadystatechange = function () {
                if (req.readyState === 4 && req.status === 200) {
                    var response = req.responseText;
                    var lenders = JSON.parse(response);
                    for (var i = 0; i < lenders.length; i++) {
                        list += "<li><a href=&#39;" + lenders[i].url + "&#39;>" + lenders[i].name + "</a>";
                    }
                    ad.innerHTML = "<ul>" + list + "</ul>";
                }
            }
        }
        // 在html的<canvas>中用图表展示月度贷款余额、利息和资产收益
        // 如果不传入参数的话,则清空之前的图表数据
        function chart(principal, interest, monthly, payments){
            var graph = document.getElementById(&#39;graph&#39;);
            graph.width = graph.width; //清除并重置画布
            if (arguments.length === 0 || !graph.getContext)
                return;
            // 获得画布元素的‘context’对象,这个对象定义了一组绘画api
            var g = graph.getContext(&#39;2d&#39;);
            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 = &#39;#f88&#39;;
            g.fill();
            g.font = &#39;blod 12px sans-serif&#39;;
            g.fillText(&#39;Total Interest Payments&#39;, 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 = &#39;green&#39;;
            g.fill();
            g.fillText(&#39;Total Equity&#39;, 20, 35);
            // 再次循环,余额数据显示为黑色粗线条
            var bal = principal;
            g.beginPath();
            g.moveTo(paymentToX(p), amountToY(bal));
            for (var p = 0; p < payments; p++) {
                var thisMonthsInterest = bal * interest;
                bal -= (monthly - thisMonthsInterest);
                g.lineTo(paymentToX(p), amountToY(bal));
            }
            g.lineWidth = 3;
            g.stroke();
            g.fillStyle = &#39;black&#39;;
            g.fillText(&#39;Loan Balance&#39;, 20, 50);
            // 将年度数据在x轴做标记

            g.textAlign = &#39;center&#39;;
            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(&#39;Year&#39;, x, y - 5);
                if (year % 5 === 0 && year * 12 !== payments)
                    g.fillText(String(year), x, y - 5);
            }
            g.textAlign = &#39;right&#39;;
            g.textBaseline = &#39;middle&#39;;
            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>
Copier après la connexion

Articles connexes :

Code javascript pur pour implémenter la fonction de calculatrice (trois méthodes)

Comment implémenter la fonction de calculatrice en javascript

Vidéos associées :

Calculatrice version Web - 8 jours pour apprendre le didacticiel vidéo javascript

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal