[读码时间] 数组求和

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

<!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
原文地址:https://www.cnblogs.com/sx00xs/p/6436004.html