表格排序

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>表格排序</title>
    <link rel="stylesheet" href="tablechange.css" type="text/css"/>
</head>
<body>
<div class="box">
    <table id="tab" cellspacing="0" cellpadding="0">
        <thead>
        <tr>
            <th>姓名</th>
            <th class="cursor">年龄</th>
            <th class="cursor">武力</th>
            <th class="cursor">性别</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<!--引入JS是有顺序限制的:根据js之间的依赖关系,按照顺序一次引入,顺序一旦出现问题,就会发生错误-->
<script type="text/javascript" charset="utf-8" src="utils.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
</body>
</html>
/*css*/
@charset "utf-8";
* {
    margin: 0;
    padding: 0;
    font-family: "微软雅黑";
    font-size: 14px;
    -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
}
.box {
    width: 400px;
    margin: 20px auto;
    padding: 20px;
    border: 1px solid green;
    border-radius: 10px;
    box-shadow: 3px 3px 10px lightblue;
}
.box thead {
    background: green;
    color: #FFF;
}
.box thead tr {
    height: 35px;
}
.box thead tr th {
    width: 100px;
    text-align: center;
}
.box thead tr th.cursor{
    cursor: pointer;
}
.box tbody tr {
    height: 30px;
}
.box tbody tr.bg {
    background: lightgreen;
}
.box tbody tr td {
    width: 100px;
    text-align: center;
}
/*main.js*/
//想要操作谁就先获取谁
var oTab = document.getElementById("tab");
var tHead = oTab.tHead;
var oThs = tHead.rows[0].cells;
var tBody = oTab.tBodies[0];
var oRows = tBody.rows;
var data = null;
//1、首先获取后台(data.txt)中的数据“JSON格式的字符串”->Ajax(async javascript and xml)
//1)首先创建一个Ajax对象
var xhr = new XMLHttpRequest;
//2)打开我们需要请求数据的那个文件地址
xhr.open("get", "http://img-ytbx.oss-cn-beijing.aliyuncs.com/WXassets/css/greenChannel/data.txt", true);
//3)监听请求状态
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        var val = xhr.responseText;
        data = utils.jsonParse(val);
        bind();
        changeBg();
    }
};
//4)发送请求
xhr.send(null);
//2、实现我们的数据绑定(动态创建、字符串拼接、文档碎片),今天用文档碎片
function bind() {
    var frg = document.createDocumentFragment();
    for (var i = 0; i < data.length; i++) {
        var cur = data[i];
        var oTr = document.createElement("tr");//每一次循环创建一个TR,每一个TR还需要创建四个TD,因为每一个对象中有四组键值对
        for (var key in cur) {
            var oTd = document.createElement("td");
            //对性别进行特殊处理,0为男,1为女
            if (key === "sex") {
                oTd.innerHTML = cur[key] === 0 ? "男" : "女";
            } else {
                oTd.innerHTML = cur[key];
            }
            oTr.appendChild(oTd);
        }
        frg.appendChild(oTr);
    }
    tBody.appendChild(frg);
    frg = null;
}
//3、实现隔行变色
function changeBg() {
    for (var i = 0; i < oRows.length; i++) {
        oRows[i].className = i % 2 === 1 ? "bg" : null;
    }
}
//4、编写表格排序的方法:实现按照年龄这一列进行排序
function sort(n) {//n是当前点击这一列的索引
    //把存储所有行的类数组转换为数组
    var _this = this;
    var ary = utils.listToArray(oRows);
    //给数组进行排序:按照每一行第二列中的内容由小到大进行排序
    //点击当前列,需要让其他的列的flag存储的值回归到初始值-1,这样在返回点击其他的列,才是按照升序排列的
    for (var k = 0; k < oThs.length; k++) {
        if (oThs[k] !== this) {
            oThs[k].flag = -1;
        }
    }
    _this.flag *= -1;
    ary.sort(function (a, b) {
        var curInn = a.cells[n].innerHTML, nexInn = b.cells[n].innerHTML;
        var curInnNum = parseFloat(a.cells[n].innerHTML), nexInnNum = parseFloat(b.cells[n].innerHTML);
        if (isNaN(curInnNum) || isNaN(nexInnNum)) {
            return curInn.localeCompare(nexInn) * _this.flag;
        } else {
            return (curInnNum - nexInnNum) * _this.flag;
        }
    });
    //按照ary中的最新顺序,把每一行重新的添加到tBody中
    var frg = document.createDocumentFragment();
    for (var i = 0; i < ary.length; i++) {
        frg.appendChild(ary[i]);
    }
    tBody.appendChild(frg);
    frg = null;
    //重新实现隔行变色,执行changeBg();
    changeBg();
}
//5、点击排序:所有具有class="cursor"这个样式的列都可以实现点击排序
for (var i = 0; i < oThs.length; i++) {
    var curTh = oThs[i];
    if (curTh.className === "cursor") {
        curTh.index = i;//用来存储索引的
        curTh.flag = -1;//用来实现升降序的
        curTh.onclick = function () {
            sort.call(this, this.index);
        }
    }
}
/*utils.js*/
var utils = {
    //->listToArray:实现将类数组转换为数组
    listToArray: function (likeAry) {
        var ary = [];
        try {
            ary = Array.prototype.slice.call(likeAry);
        } catch (e) {
            for (var i = 0; i < likeAry.length; i++) {
                ary[ary.length] = likeAry[i];
            }
        }
        return ary;
    },
    //jsonParse:把JSON格式的字符串转换为JSON格式的对象
    jsonParse: function (str) {
        /*var val = null;
         try {
         val = JSON.parse(str);
         } catch (e) {
         val = eval("(" + str + ")");
         }
         return val;*/
        return "JSON" in window ? JSON.parse(str) : eval("(" + str + ")");
    }
};
//data.txt
[{"name":"令狐冲","age":24,"score":98,"sex":0},{"name":"任盈盈","age":22,"score":80,"sex":1},{"name":"岳灵珊","age":21,"score":88,"sex":1},{"name":"岳不群","age":58,"score":96,"sex":0},{"name":"李凝之","age":23,"score":90,"sex":0},{"name":"东方不败","age":30,"score":100,"sex":1}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值