<! DOCTYPE html>
<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>
<body>
<table id= "table" class= "table" >
<thead>
<tr class= "Bg2" >
<th class= "cursor" > name </th>
<th class= "cursor" > Age </th>
<th class= "cursor" > Score </th>
<th class= "cursor" > Gender </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? " Male ":" Female ";
}
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 (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>
Attached file: data.txt
[
{"Name": "Zhao Eldest", "Age": "Score": "June", "Sex": 0},
{"Name": "Money Two Girl", "Age": "Score": "The", "Sex": 1},
{"Name": "Sun Sanxiang", "Age": $, "score": +, "Sex": 1},
{"Name": "Li Shiyi", "age": +, "score": +, "Sex": 0},
{"Name": "Miss Zhou", "Age": $1, "score": "A", "sex":
{"Name": "Wu Sangui", "age": +, "score": +, "Sex": 0}
]
JavaScript: Table Sort