文档章节

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

h
 hujiapeng
发布于 2016/12/28 09:43
字数 1022
阅读 1
收藏 0

示例:javascript贷款计算器

  相关技术:

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

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

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

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

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

    6、如何利用<canvas>元素绘图。

 

<!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>
贷款计算器

 

© 著作权归作者所有

h
粉丝 0
博文 100
码字总数 60569
作品 0
海淀
私信 提问
OSChina 第 21 期高手问答 —— ExtJS

OSCHINA 本期高手问答我们请来了《Ext JS权威指南》一书的作者 —— @黄灯桥 为大家解答关于 ExtJS 使用方面的各种问题。 黄灯桥(网名:上将军),资深Web技术专家,拥有10余年工作经验,一...

红薯
2012/06/24
6.9K
98
javascript——从「最被误解的语言」到「最流行的语言」

JavaScript曾是“世界上最被误解的语言”,因为它担负太多的特性,包括糟糕的交互和失败的设计,但随着Ajax的到来,JavaScript“从最受误解的编程语言演变为最流行的语言”,这除了幸运之外,...

modernizr
2014/05/20
1K
12
[]==''返回?为什么?运算符==进行了什么操作?

对的你没看错,这是道很基础的面试题,昨天刚好面试到了,没答上出来。 []==''返回? 直接说答案吧,返回是 为什么? 如果你看《Javascript权威指南第6版》的话,从75-76页里面关于==的转换 ...

tony1475333400936
2018/12/08
0
0
前端学习之路(从入门到入坑...)

学习前端两年多了,拿了阿里巴巴实现offer,想结合个人经历总结的前端入门方法,总结从零基础到具备前端基本技能的道路、学习方法、资料。由于能力有限,不能保证面面俱到,只是作为入门参考...

阿小庆
2018/06/14
0
0
分享51本关于JavaScript方面的学习书籍(免费下载)

分享51本关于JavaScript方面的学习书籍(免费下载) 1、JavaScript面向对象15分钟教程 2、原型、作用域、闭包的完整解释 3、Javascript面向对象特性实现(封装、继承、接口) 4、JavaScript面向...

邓剑彬
2012/12/02
1K
12

没有更多内容

加载失败,请刷新页面

加载更多

kibana汉化

kibana5 / 6 需要下载补丁包,https://github.com/anbai-inc/Kibana_Hanization 其中 v6 版本原生支持国际化,只需要添加资源文件并且配置即可 kibana7 v7版本官方内置汉化资源,在配置文件 ...

细肉云吞
23分钟前
5
0
spring boot 自定义日志 log4j2

使用默认的日志在实际开发中会存在很多问题,比如备份文件名称无法自动重命名、各个等级的日志被放在一个文件中等,所以实际开发中为了更好满足我们的需求,我们一般都会自定义采用配置的方式...

雷开你的门
27分钟前
7
0
PCB设计-Allegro软件入门系列-设计参数配置(上)

前言 经历了导入网表,和放置器件后,我们就要画板子了,但是必要的设计参数也要先准备好,磨刀不误砍柴工。 《一》显示参数 这里主要设置DRC报错标志大小和飞线显示类型 (1)DRC标志可以适当...

demyar
28分钟前
7
0
js实现微博、微信分享

html <!-- 分享 --><div class="share-box"> <b style="vertical-align: middle;">分享到:</b> <a title="分享到新浪微博" class="shareSina"><span class="share-icon"></span><......

张兴华ZHero
44分钟前
7
0
创龙TMS320DM8168浮点DSP C674x + ARM Cortex-A8的CPU、NAND FLASH、NOR FLASH

TL6678-EasyEVM是广州创龙基于SOM-TL6678核心板而研发的一款多核高性能DSP开发板。开发板采用核心板+底板方式,底板采用沉金无铅工艺的四层板设计,尺寸为200mm*106.65mm,它为用户提供了SOM...

Tronlong创龙
47分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部