ホームページ >ウェブフロントエンド >jsチュートリアル >JavaScript はテーブルのソートを実装します
<スクリプト言語="JavaScript">
var dom = (document.getElementsByTagName) ?真/偽;
var ie5 = (document.getElementsByTagName && document.all) ?真/偽;
var arrowUp、arrowDown;
if (ie5 || dom)
initSortTable();
function initSortTable() {
arrowUp = document.createElement("SPAN");
var tn = document.createTextNode("↑");
arrowUp.appendChild(tn);
arrowUp.className = "矢印";
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
}
var start = 新しい日付;
window.status = "データを並べ替えています...";
a.sort(compareByColumn(nCol,bDesc,sType));
window.status = "データの並べ替えが完了しました";
for (var i = 0; i
window.status = "行 " + (i + 1) + " of " + trl +
" (費やした時間: " + (新しい日付 - 開始) + "ミリ秒)";
}
// オンソートを確認します
if (typeof tableNode.onsort == "string")
tableNode.onsort = new Function("", tableNode.onsort);
if (typeof tableNode.onsort == "関数")
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("%", ""));
}
関数compareByColumn(nCol, bDescending, sType) {
var c = nCol;
var d = b降順;
var fTypeCast = 文字列;
if (sType == "数値")
fTypeCast = 数値;
else if (sType == "Date")
fTypeCast = parseDate;
else if (sType == "CaseInsensitiveString")
fTypeCast = CaseInsensitiveString;
else if (sType == "パーセント")
fTypeCast = パーセント;
return 関数 (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;
0 を返します。
};
}
関数 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 = "待機";
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)