1、先引入含有如下插件的js
(function($){
//插件
$.extend($,{
//命名空间
sortTable:{
sort:function(tableId,Idx,that){
var table = document.getElementById(tableId);
var tbody = table.tBodies[0];
var tr = tbody.rows;
var trValue = new Array();
for (var i=0; i<tr.length; i++ ) {
trValue[i] = tr[i]; //将表格中各行的信息存储在新建的数组中
}
if (tbody.sortCol == Idx) {
trValue.reverse(); //如果该列已经进行排序过了,则直接对其反序排列
if(that.children[0].className=='home-triangle-down') {
that.children[0].className="home-triangle-up";
} else {
that.children[0].className="home-triangle-down";
}
} else {
trValue.sort(function(tr1, tr2){
var value1 = tr1.cells[Idx].innerHTML;
var value2 = tr2.cells[Idx].innerHTML;
return value2.localeCompare(value1);
});
that.children[0].className="home-triangle-down";
}
var fragment = document.createDocumentFragment(); //新建一个代码片段,用于保存排序后的结果
for (var i=0; i<trValue.length; i++ ) {
fragment.appendChild(trValue[i]);
}
tbody.appendChild(fragment); //将排序的结果替换掉之前的值
tbody.sortCol = Idx;
}
}
});
})(jQuery);
2、添加排序的箭头(使用css画箭头图标):
a>向上的箭头
.home-triangle-up{
border-color: #349cd3 transparent;
border-width: 0px 6px 6px 6px;
border-style: solid;
/* float: right; */
margin: 0px 0px 3px 10px;
display: inline-block;
}
b>向下的箭头
.home-triangle-down{
border-color: #349cd3 transparent;
border-width: 5px 5px 0px 5px;
border-style: solid;
/* float: right; */
margin: 0px 0px 3px 10px;
display: inline-block;
}
3、绑定点击事件
<th style="width:150px;cursor: pointer;" onclick="$.sortTable.sort('D_PREPAY_INFO_LIST', 9, this)">生效日期<span class="home-triangle-down"></span></th>