html页面点击表头排序,HTML中单击Table表头实现排序

本代码基于jquery,如下:

/*

* The object TableSort can be used as a tool class

*/

var TableSort = {

init: function (TableId) {

this.setDataArray(TableId);

this.table = $("#" + TableId);

$("#" + TableId + " tr:first td").bind("click",this.sort);

},

table:null,

dataArray: [],

htmlArray: {},

setDataArray: function (TableId) {

$("#" + TableId + " tr").each(function (i) {

var tr = $(this);

if (i != 0) {

var temp = [];

temp.push(tr.attr("rowid"));

tr.find("td").each(function () {

temp.push($(this).text());

});

TableSort.dataArray.push(temp);

TableSort.htmlArray[tr.attr("rowid")] = tr.clone();

}

});

},

sort: function () {

var td = $(this);

var index = td.index();

var sortIndex = index + 1;

var currentSort = td.attr("sortType") || "ASC";

if (currentSort == "ASC") {

TableSort.dataArray = TableSort.multiArraySort(TableSort.dataArray, "DESC", sortIndex);

td.attr("sortType", "DESC");

} else {

TableSort.dataArray = TableSort.multiArraySort(TableSort.dataArray, "ASC", sortIndex);

td.attr("sortType", "ASC");

}

td.siblings().attr("sortType", "");

//refresh the table

TableSort.table.find("tr:gt(0)").remove();

for (var i = 0, len = TableSort.dataArray.length; i < len; i++) {

var rowid = TableSort.dataArray[i][0];

TableSort.table.children().append(TableSort.htmlArray[rowid]);

}

},

multiArraySort: function (array, type, index) {

var resultArray = array;

if(type == "ASC"){

resultArray.sort(function (a, b) {

//String is the default type of content,the number should return b[sortIndex]-a[sortIndex].

return a[index].localeCompare(b[index]);

});

return resultArray;

} else if (type == "DESC") {

resultArray.sort(function (a, b) {

return b[index].localeCompare(a[index]);

});

return resultArray;

} else {

console.log("The argument of 'multiArraySort' value does not match the type that this argument expects. " +

"Check that the argument value is appropriate to the type expected by this argument, and then try again.");

return null;

}

}

};

使用时直接如下调用:

TableSort.init("tableId");



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值