欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

JavaScript实现表格排序

程序员文章站 2022-04-23 21:37:43
...
<SCRIPT LANGUAGE="JavaScript">
var dom = (document.getElementsByTagName) ? true : false;
var ie5 = (document.getElementsByTagName && document.all) ? true : false;
var arrowUp, arrowDown;
if (ie5 || dom)
initSortTable();
function initSortTable() {
arrowUp = document.createElement("SPAN");
var tn = document.createTextNode("↑");
arrowUp.appendChild(tn);
arrowUp.className = "arrow";
arrowDown = document.createElement("SPAN");
var tn = document.createTextNode("↓");
arrowDown.appendChild(tn);
arrowDown.className = "arrow";
}
function sortTable(tableNode, nCol, bDesc, sType) {
var tBody = tableNode.tBodies[0];
var trs = tBody.rows;
var trl= trs.length;
var a = new Array();
for (var i = 0; i < trl; i++) {
a[i] = trs[i];
}
var start = new Date;
window.status = "Sorting data...";
a.sort(compareByColumn(nCol,bDesc,sType));
window.status = "Sorting data done";
for (var i = 0; i < trl; i++) {
tBody.appendChild(a[i]);
window.status = "Updating row " + (i + 1) + " of " + trl +
" (Time spent: " + (new Date - start) + "ms)";
}
// check for onsort
if (typeof tableNode.onsort == "string")
tableNode.onsort = new Function("", tableNode.onsort);
if (typeof tableNode.onsort == "function")
tableNode.onsort();
}
function CaseInsensitiveString(s) {
return String(s).toUpperCase();
}
function parseDate(s) {
return Date.parse(s.replace(/-/g, /));
}
function toNumber(s) {
return Number(s.replace(/[^0-9.]/g, ""));
}
function Percent(s) {
return Number(s.replace("%", ""));
}
function compareByColumn(nCol, bDescending, sType) {
var c = nCol;
var d = bDescending;
var fTypeCast = String;
if (sType == "Number")
fTypeCast = Number;
else if (sType == "Date")
fTypeCast = parseDate;
else if (sType == "CaseInsensitiveString")
fTypeCast = CaseInsensitiveString;
else if (sType == "Percent")
fTypeCast = Percent;
return function (n1, n2) {
if (fTypeCast(getInnerText(n1.cells[c])) < fTypeCast(getInnerText(n2.cells[c])))
return d ? -1 : +1;
if (fTypeCast(getInnerText(n1.cells[c])) > fTypeCast(getInnerText(n2.cells[c])))
return d ? +1 : -1;
return 0;
};
}
function sortColumnWithHold(e) {
var el = ie5 ? e.srcElement : e.target;
var table = getParent(el, "TABLE");
var oldCursor = table.style.cursor;
var oldClick = table.onclick;
table.style.cursor = "wait";
table.onclick = null;
var fakeEvent = {srcElement : e.srcElement, target : e.target};
window.setTimeout(function () {
sortColumn(fakeEvent);
table.style.cursor = oldCursor;
table.onclick = oldClick;
}, 100);
}
function sortColumn(e) {
var tmp = e.target ? e.target : e.srcElement;
var tHeadParent = getParent(tmp, "THEAD");
var el = getParent(tmp, "TD");
if (tHeadParent == null)
相关标签: JavaScript