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

Stella981
• 阅读 599

示例:javascript贷款计算器

  相关技术:

    1、如何在文档中查找元素;

    2、如何通过表单input元素来获取用户的输入数据;

    3、如何通过文档元素来设置HTML内容;

    4、如何将数据存储在浏览器中;

    5、如何使用脚本发起HTTP请求;

    6、如何利用元素绘图。

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

<!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>

贷款计算器

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Java修道之路,问鼎巅峰,我辈代码修仙法力齐天
<center<fontcolor00FF7Fsize5face"黑体"代码尽头谁为峰,一见秃头道成空。</font<center<fontcolor00FF00size5face"黑体"编程修真路破折,一步一劫渡飞升。</font众所周知,编程修真有八大境界:1.Javase练气筑基2.数据库结丹3.web前端元婴4.Jav
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这