时间:2021-09-02 10:08:27 | 栏目:jquery | 点击:次
最近要对报表数组进行排序,在前端处理如下:
首先在前台页面加载时对每行tr添加自定义的属性data-sort-field-ftime
,属性值为要排序的字段的值(我的是数字比较方便):
$.each(jsonarray, function(i, obj) { troptions += "<tr data-sort-field-ftime=\""+obj.paiming+"\">"; troptions += "<td>"+(Number(obj.cdsPrem)/unitnow).toFixed(dotnow)+"</td>"; troptions += "<td>"+(Number(obj.cdjPrem)/unitnow).toFixed(dotnow)+"</td>"; troptions += "<td>"+(Number(obj.sumPrem)/unitnow).toFixed(dotnow)+"</td>"; troptions += "<td>"+obj.paiming+"</td>"; troptions += "</tr>"; });
在要排序的表头添加onchange事件,以下为onchange
事件:
//排序处理 function changepm(){ var sortType=$("#pm").val(); var $trList = $("#ta tbody > tr");//获取现有tr对象 //冒泡排序 for (var i = 0; i < $trList.length - 1; i++) { for (var j = 0; j < $trList.length - 1 - i; j++) { var value1 = parseInt($trList[j].attributes["data-sort-field-ftime"].nodeValue); var value2 = parseInt($trList[j + 1].attributes["data-sort-field-ftime"].nodeValue); if (sortType === "asc" ? value1 > value2 : value1 < value2) { var $temp = $trList[j]; $trList[j] = null; $trList[j] = $trList[j + 1]; $trList[j + 1] = null; $trList[j + 1] = $temp; } } } //返回排序后的tr集合 //将原来的tr清空,再将排序后的tr插入到table的dom中 console.log($trList); $trList.appendTo($("#ta > tbody").empty()); }