JavaScript:表格排序
Posted WEB前端工程师----钱成
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript:表格排序相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#table{
width:600px;
border:3px solid darkgreen;
margin:20px auto;
text-align: center;
-webkit-user-select:none;
-moz-user-select:none;
-o-user-select:none;
-ms-user-select:none;
}
#table tr{
height:40px;
line-height:40px;
}
.bg0{
background: mediumvioletred;
}
.bg1{
background: greenyellow;
}
.bg2{
background: yellow;
}
</style>
</head>
<body>
<table id="table" class="table">
<thead>
<tr class="bg2">
<th class="cursor">姓名</th>
<th class="cursor">年龄</th>
<th class="cursor">分数</th>
<th class="cursor">性别</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var table=document.getElementById("table");
var th=table.tHead.rows[0].cells;
var body=table.tBodies[0];
var row=body.rows;
var data=null;
getData();
function getData(){
var xml=new XMLHttpRequest();
xml.open("get","data.txt",false);
xml.onreadystatechange= function () {
if(xml.readyState===4 && /^2\d{2}$/.test(xml.status)){
data=jsonParse(xml.responseText);
}
};
xml.send(null);
}
function jsonParse(jsonStr){
return "JSON" in window ? JSON.parse(jsonStr):eval("("+jsonStr+")");
}
bind();
function bind(){
var frg=document.createDocumentFragment();
for(var i=0;i<data.length;i++){
var cur=data[i];
var tr=document.createElement("tr");
for(var attr in cur){
if(attr==="sex"){
cur[attr]=cur[attr]===0?"男":"女";
}
var td=document.createElement("td");
td.innerHTML=cur[attr];
tr.appendChild(td);
}
frg.appendChild(tr);
}
body.appendChild(frg);
frg=null;
}
changeColor();
function changeColor(){
for(var i=0;i<row.length;i++){
row[i].className="bg"+i%2;
}
}
function makeArray(arg){
var ary=[];
try{
ary=Array.prototype.slice.call(arg);
}catch (e){
for(var i=0;i<arg.length;i++){
ary.push(arg[i]);
}
}
return ary;
}
function sort(n){
var that=this;
for(var i=0;i<th.length;i++){
th[i].flag=i===n?that.flag*=-1:-1;
}
var ary=makeArray(row);
ary.sort(function(a,b){
a= a.cells[n].innerHTML;
b= b.cells[n].innerHTML;
if(isNaN(a) && isNaN(b)){
return a.localeCompare(b)*that.flag;
}
return (a-b)*that.flag;
});
var frg=null;
for( i=0;i<ary.length;i++){
frg=ary[i];
body.appendChild(frg);
}
changeColor();
}
for(var i=0;i<th.length;i++){
if(th[i].className==="cursor"){
th[i].flag=-1;
th[i].index=i;
th[i].onclick=function(){
sort.call(this,this.index);
}
}
}
</script>
</body>
</html>
附文件:data.txt
[
{"name": "赵老大", "age": 45, "score": 89, "sex": 0},
{"name": "钱二妞", "age": 24, "score": 67, "sex": 1},
{"name": "孙三娘", "age": 38, "score": 79, "sex": 1},
{"name": "李四爷", "age": 30, "score": 80, "sex": 0},
{"name": "周姑娘", "age": 65, "score": 56, "sex": 1},
{"name": "吴三桂", "age": 26, "score": 26, "sex": 0}
]
以上是关于JavaScript:表格排序的主要内容,如果未能解决你的问题,请参考以下文章