<title>JS表格排序</title>
<script type="text/javascript">
var tableSort = {};
(function() {
var oTable = {};
var cellStatus = {};
var sortCells = {};
var limit = {};
var $ = function(id) {
return document.getElementById(id);
}
var objKeyExists = function(key, search) {
if (typeof key != 'number' && typeof key != 'string') {
return false;
}
for (k in search) {
if (k == key) {
return true;
}
}
return false;
}
var _addEvent = function(tableId, cellId) {
oTable[tableId].rows[0].cells[cellId].onclick = function() {
tableSort.sort(tableId, cellId);
}
}
var _addStyle = function(tableId, cellId) {
oTable[tableId].rows[0].cells[cellId].style.cursor = 'pointer';
}
var _addTitle = function(tableId, cellId) {
oTable[tableId].rows[0].cells[cellId].title = '点击排序';
}
var _sortTable = function(tableId, cellId) {
var rows = oTable[tableId].tBodies[0].rows;
var _rows = [];
for (var i = 1; i < rows.length; i++) {
_rows.push(rows[i]);
}
var status = -1;
if (objKeyExists(cellId, cellStatus[tableId])) {
status = 0 - cellStatus[tableId][cellId];
}
cellStatus[tableId][cellId] = status;
if (status == 1) {
oTable[tableId].rows[0].cells[cellId].innerHTML += ' <span style="font-family:webdings;">5</span>';
_rows.sort((function(id){
return function(a, b) {
return _sort(a, b, id);
}
}(cellId)));
} else {
oTable[tableId].rows[0].cells[cellId].innerHTML += ' <span style="font-family:webdings;">6</span>';
_rows.sort((function(id){
return function(a, b) {
return _rsort(a, b, id);
}
}(cellId)));
}
var oFragment = document.createDocumentFragment();
for (var i = 0; i < _rows.length; i++) {
_rows[i].className = i % 2 ? 'tr' : 'tr_spec';
_rows[i].cells[0].className = i % 2 ? 'td_spec2' : 'td_spec1';
if (limit[tableId] > 0) {
if (i >= limit[tableId]) {
_rows[i].style.display = 'none';
} else {
_rows[i].style.display = '';
}
}
oFragment.appendChild(_rows[i]);
}
oTable[tableId].tBodies[0].appendChild(oFragment);
}
var _cleanStatus = function(tableId, cellId) {
for(var i = 0; i < sortCells[tableId].length; i++) {
oTable[tableId].rows[0].cells[sortCells[tableId][i]].innerHTML = oTable[tableId].rows[0].cells[sortCells[tableId][i]].innerHTML.replace(/ <span style=\"font-family\: webdings\">[56]<\/span>$/ig, '');
}
}
var _sort = function(a, b, id) {
var param1 = a.cells[id].innerText;
var param2 = b.cells[id].innerText;
param1 = param1.replace(/[^\d.-]/g, '');
param2 = param2.replace(/[^\d.-]/g, '');
if (param1 == '-' || param1 == '') {
return 1;
}
if (param2 == '-' || param2 == '') {
return -1;
}
//如果两个参数均为字符串类型
if (isNaN(param1) && isNaN(param2)){
return param1.localeCompare(param2);
}
//如果参数1为数字,参数2为字符串
if (!isNaN(param1) && isNaN(param2)){
return -1;
}
//如果参数1为字符串,参数2为数字
if (isNaN(param1) && !isNaN(param2)){
return 1;
}
//如果两个参数均为数字
if (!isNaN(param1) && !isNaN(param2)){
if (Number(param1) > Number(param2)) {
return 1;
}
if (Number(param1) == Number(param2)) {
return 0;
�
评论1
最新资源