-
Notifications
You must be signed in to change notification settings - Fork 0
/
table_sort.js
48 lines (44 loc) · 1.33 KB
/
table_sort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 传入Table,为其绑定点击排序事件
**/
function enhanceTable(table) {
var theadArr = [];
var sortFlat = false;
var theadNode = table.tHead.rows[0].cells;
//先储存到一个array中, 方便后面去排序
for (var i=0; i<theadNode.length; i++) {
theadArr.push(theadNode[i]);
}
//table thead 的点击回调函数
function onClickTHead(event) {
sortTable(table, theadArr.indexOf(event.target), sortFlat);
sortFlat = !sortFlat;
}
//排序Table函数
function sortTable(table, indexOfColumn, isAsc) {
var arrTableRows;
try {
arrTableRows = Array.prototype.slice.call(table.tBodies[0].rows);
} catch (ex) {
arrTableRows = []
for(var i=0; i<table.tBodies[0].rows.length; i++) {
arrTableRows.push( table.tBodies[0].rows[i] );
}
}
//简单起见,排序规则就是字符串比较,一般情况够用了
arrTableRows.sort( function (a, b) {
return isAsc==true?
(a.cells[indexOfColumn].innerHTML > b.cells[indexOfColumn].innerHTML) :
(a.cells[indexOfColumn].innerHTML < b.cells[indexOfColumn].innerHTML);
});
var markUp = "";
for(var i=0; i<arrTableRows.length; i++) {
markUp += "<tr>";
markUp += arrTableRows[i].innerHTML
markUp += "</tr>";
}
table.tBodies[0].innerHTML = markUp;
return arrTableRows;
}
table.tHead.addEventListener("click", onClickTHead);
}