项目中经常遇到对时间排序、对价格排序。。,这个算法可以适用所有的数字排序,注意以下几步:
1.
//时间排序 $comParaters.div_SortTimeZ.unbind('click'); $comParaters.div_SortTimeZ.click(function(){ //这只是一个点击事件,调用的函数最重要 orderByDate(); });2.
//按时间排序 function orderByDate() { if ($comParaters.btnSortTime.data('Sort') == "DESC") { //给你点击的标签设置一个属性'Sort'='DESC' FlightSort('ASC', 'sortTime'); $comParaters.btnSortTime.data('Sort', 'ASC'); //点击之后给你的属性重新定义,以便来回切换 //从早到晚 } else { FlightSort('DESC', 'sortTime'); $comParaters.btnSortTime.removeClass("upIcon").addClass("downIcon"); $comParaters.btnSortTime.data('Sort', 'DESC'); //从晚到早 } return false; }3.
//排序专用 function FlightSort(objType, objValue) { var $FlightDataContainer = $('#FlightDataContainer'); //获取你需要排序的地方的id var $FlightDataSort = $FlightDataContainer.find('.tempclass'); var map = []; $.each($FlightDataSort, function(i, n) { var obj = {}; obj.Insort = $(this).attr(objValue); //Insort是你现在要获取到的数字,如果是时间或者日期可以用replace, obj.item = this; //转化为数字 this是你当前需要比较的那个数 map.push(obj); }); if (objType == 'ASC') { //升序 map.sort(sortIntAsc); } else { map.sort(sortIntDesc); //降序 } for (var j = 0; j < map.length; j++) { $FlightDataContainer[0].appendChild(map[j].item); //将这个排序好的数据重新追加到你的代码里 } }
4.
//降序 function sortIntDesc(a, b) { return a.Insort * 1 < b.Insort * 1 ? 1 : -1; } //升序 function sortIntAsc(a, b) { return a.Insort * 1 > b.Insort * 1 ? 1 : -1; }以上的这些代码可以使你的排序更加完善。