zoukankan      html  css  js  c++  java
  • [读码时间] 数组求和

    说明:代码来自网络。注释为笔者学习时添加。

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>数组求和</title>
        <style>
            body{
                color:#999;/*浅黑色*/
                font:12px/1.5 Tahoma;/*行高18*/
            }
            #outer{
                width:500px;
                margin:0 auto;/*左右置中*/
            }
            #outer input{
                padding:3px;
                border:1px solid #ccc;/*边框灰色*/
                font-family:inherit;
                width:220px;
                margin-right:10px;/*右外边距*/
            }
            .sum{
                font-size:30px;/*字号*/
                color:red;/*文字颜色*/
            }
        </style>
        <script>
            window.onload = function () {
                var oBtn = document.getElementsByTagName("button")[0]; //获取button中的第一个
                var oInput = document.getElementsByTagName("input")[0];//获取input中的第一个
                var oStrong = document.getElementsByTagName("strong")[0];//获取strong中的第一个
                oInput.onkeyup = function () {//注册keyup事件
                    this.value = this.value.replace(/[^(d)|(,)]/, "");//调用replace方法去除开头的空格或逗号
                }
                oBtn.onclick = function () {
                    var sum = 0;
                    var oInput = document.getElementsByTagName("input")[0].value.split(",");//获取input输入值,调用split以逗号为分隔符,返回一数组
                    for (var i in oInput) {  
                        sum += parseInt(oInput[i]);//循环把数组元素传递给parseInt解析为数字相加
                    }
                    oStrong.innerHTML = sum;//把结果赋值给strong元素
                }
            }
        </script>
    </head>
    <body>
        <!--div包裹,strong元素用来显示结果-->
        <div id="outer">
            <label><input type="text" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15" /><span>输入数字求和,数字之间用半角","号分隔</span></label>
            <p><button>求和</button></p>
            <strong class="sum"></strong>
        </div>
    </body>
    </html>
    View Code
  • 相关阅读:
    解决执行sql脚本报错:没有足够的内存继续执行程序。
    正则表达式学习
    art-template模板引擎循环嵌套
    textarea 设置最长字数和显示剩余字数
    display:table-cell
    js 发送 ajax 是数组 后台循环 发送json 到前台的方法
    js 函数内数据调用
    Angular 原文输出
    Angular 路由跳转
    JQ 按钮实现两种功能
  • 原文地址:https://www.cnblogs.com/sx00xs/p/6436004.html
Copyright © 2011-2022 走看看