一个简单的js脚本实现表格排序

在项目中需要点击表格的列头来进行行排序,不需要进行异步刷新,所以写了一个js脚本实现的客户排序,主要使用的是js源生的一个方法sort。

简单的看一下代码:

var up = "↑";
var down = "↓";

/*
    table sort
    */
    function tableSort($rows, orderby, order) {
        $rows.sort(function ($row1, $row2) {
            var val1 = $.trim($("td:eq(" + orderby + ")", $row1).text());
            var val2 = $.trim($("td:eq(" + orderby + ")", $row2).text());
            if (orderby == '3') {
          //if orderby is date
if (val1 == '') {//if date1 is null if (val2 == '') {//if tow date both null return 0; } else { return 1 * order; } } else { if (val2 == '') { return -1 * order; } } return (new Date(val1) - new Date(val2)) * order; //date } else { return val1.localeCompare(val2) * order; //string } //return val1 - val2; //number }); } function titleClick() { $("th", "table").toggle( function () { var $tbody = $(this).parent().parent(); var $rows = $tbody.find("tr:has(td)"); if ($rows.length > 1) {// if this table has tr tableSort($rows, $(this).attr('name'), 1);
         //when sorted, add all tr into tbody and refresh this table
for (var i = 0; i < $rows.length; i++) { $tbody.append($rows.eq(i)); } }        //refresh index $rows.each(function (index) { $(this).find("td:eq(0)").text(index + 1); });
        $(
"th .sort", "table").text(""); $(this).find(".sort").text(up); }, function () { var $tbody = $(this).parent().parent(); var $rows = $tbody.find("tr:has(td)"); if ($rows.length > 1) { tableSort($rows, $(this).attr('name'), -1); for (var i = 0; i < $rows.length; i++) { $tbody.append($rows.eq(i)); } } $rows.each(function (index) { $(this).find("td:eq(0)").text(index + 1); }); $("th .sort", "table").text(""); $(this).find(".sort").text(down); } ); }

行集合支持sort方法,方法内相当于一个委托,自动进行递归操作,将结果排序。order是正序或者倒序,orderby是需要排序的字段或者说列标识。

原文地址:https://www.cnblogs.com/fengyishou/p/2567375.html