Home  >  Article  >  Web Front-end  >  Detailed example of how jQuery sorts a table

Detailed example of how jQuery sorts a table

黄舟
黄舟Original
2017-08-11 13:59:201752browse

This article mainly introduces an example demonstration of jquery sorting a table. By adding the custom attribute data-sort-field-ftime and adding the onchange event in the table header, the operation process is explained in detail. Friends in need can refer to the following

Recently, the report array needs to be sorted, and the front-end processing is as follows:

First add custom attributes to each row of tr when the front page is loaded data-sort-field-ftime, the attribute value is the value of the field to be sorted (mine is more convenient with numbers):


$.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>";
      });

Add an onchange event to the header of the table to be sorted, the following is onchangeEvent:


//排序处理
  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());
  }

The above is the detailed content of Detailed example of how jQuery sorts a table. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn