- 爱易网页
-
Java教程
- 网页表格中查出的数字是文本格式怎么排序
日期:2014-05-17 浏览次数:20864 次
网页表格中查出的数字是文本格式如何排序
在网上找了如下代码实现了网页表格的排序,但是在数据库中查出的数字以文本存储,数字的排序问题无法解决,问下该如何实现排序?
<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 a = new Array();
for (var i=0; i<trs.length; i++) {
a[i] = trs[i];
}
a.sort(compareByColumn(nCol,bDesc,sType));
for (var i=0; i<a.length; i++) {
tBody.appendChild(a[i]);
}
}
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 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;
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 sortColumn(e) {
var tmp, el, tHeadParent;
if (ie5)
tmp = e.srcElement;
else if (dom)
tmp = e.target;
tHeadParent = getParent(tmp, "THEAD");
el = getParent(tmp, "TH");
if (tHeadParent == null)
return;
if (el != null) {
var p = el.parentNode;
var i;
if (el._descending) // catch the null
el._descending = false;
else
el._descending = true;
if (tHeadParent.arrow != null) {
if (tHeadParent.arrow.parentNode != el) {
tHeadParent.arrow.parentNode._descending = null;
}
tHeadParent.arrow.parentNode.removeChild(tHeadParent.arrow);
}
if (el._descending)
tHeadParent.arrow = arrowDown.cloneNode(true);
else
tHeadParent.arrow = arrowUp.cloneNode(true);
el.appendChild(tHeadParent.arrow);
// get the index of the td
for (i=0; i<p.cells.length; i++) {
if (p.cells[i] == el) break;
}
var table = getParent(el, "TABLE");
// can't fail
sortTable(table,i,el._descending, el.getAttribute("type"));
}
}
function getInnerText(el) {
if (ie5) return el.innerText; //Not needed but it is faster
var str = "";