表格排序的具体案例(包括数字和汉字排序)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>表格排序</title>
<style type="text/css">
ul,li{
margin: 0;
padding: 0;
list-style: none;
}
ul{
width: 600px;
margin: 10px auto;
border-radius: 10px;
border: 5px solid #080629;
padding: 10px;
}
li{
line-height: 30px;
width: 100%;
}
span{
display: inline-block;
width: 150px;
line-height: 40px;
text-align: center;
}
.head span{
cursor: pointer;
line-height: 40px;
background-color: yellowgreen;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.bg0{
background-color: lightcyan;
}
.bg1{
background-color: linen;
}
</style>
</head>
<body>
<ul id="tab">
<li class="head"><span>姓名</span><span>年龄</span><span>战斗力</span><span>性别</span></li>
</ul>
<script type="text/javascript">
var date = [
{"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},
{"name": "高佳睿", "age": 2, "score": -88, "sex": 1}
];
/*
获取所需元素元素
*/
var oUl = document.getElementById("tab");
//动态添加li标签方法执行
bind();
var items = oUl.getElementsByClassName("item");
var span = oUl.getElementsByClassName("head")[0].getElementsByTagName("span");
//使用js做隔行变色效果(当然css也可以)
changeColor();
//循环上边的标题,在点击的时候使之做出对应排序效果
for (var j = 0; j < span.length; j++) {
span[j].flag = -1;
(function (n) {
span[n].onclick = function () {
sort(n);
}
})(j);
}
//排序的具体方法
function sort(n) {
for (var k = 0; k < span.length; k++) {
span[k].flag = (k === n ? span[k].flag * (-1) : -1);
}
var item = Array.prototype.slice.call(items);
item.sort(function (a, b) {
var mm = a.children[n].innerHTML;
var nn = b.children[n].innerHTML;
var pre = Number(mm);
var nex = Number(nn);
if (isNaN(pre)) {
return (mm.localeCompare(nn)) * span[n].flag;
} else {
return (pre - nex) * span[n].flag;
}
});
var frg = document.createDocumentFragment();
for (var i = 0; i < item.length; i++) {
frg.appendChild(item[i]);
}
oUl.appendChild(frg);
frg = null;
changeColor();
}
//js隔行变色
function changeColor() {
for (var i = 0; i < items.length; i++) {
items[i].className = "item bg" + i % 2;
}
}
//动态添加li标签
function bind() {
var frg = document.createDocumentFragment();
for (var i = 0; i < date.length; i++) {
var cur = date[i];
var oLi = document.createElement("li");
oLi.setAttribute("class", "item");
var str = "<span>" + cur.name + "</span>" + "<span>" + cur.age + "</span>" + "<span>" + cur.score + "</span>" + "<span>" + (cur.sex === 0 ? "男" : "女") + "</span>";
oLi.innerHTML = str;
frg.appendChild(oLi);
}
oUl.appendChild(frg);
}
</script>
</body>
</html>
万人中央,我孤独的漂亮。