个性化阅读
专注于IT技术分析

如何使用纯JavaScript或jQuery在客户端对表进行排序

点击下载

本文概述

当然, 你已经检查了我们的jQuery和JavaScript最佳插件排行榜中的前7名, 并考虑了借助第三方插件对表进行排序的便捷程度。使用插件提供了好处和优势, 那就是你无需弄乱自定义代码即可订购简单的表格。图书馆已经解决了诸如处理日期等问题。

但是在某些情况下, 你不能简单地使用插件来完成此任务, 因为你要么被禁止, 要么只想自己学习如何使用它。在本文中, 我们将与你分享两种使用纯JavaScript或jQuery(如果愿意)按字母顺序对表进行排序的方法。

注意

这两种实现都期望使用<thead>(且其标头带有<th>的头)和<tbody>结构, 因此请确保如果使用任何上述方法, 则此条件得以实现。此外, 这两种方法都以相同的方式工作, 表格的第一个元素将变为可单击, 并且当单击它们时, 表格将根据其当前状态(升序或降序)进行排序。

用VanillaJS排序表

如果你仍然愿意对没有插件的表进行排序, 则必须为其编写自己的代码。以下JavaScript对象(类样式)提供了makeSortable方法, 该方法期望将表的DOM元素专门作为第一个参数:

/**
 * Modified and more readable version of the answer by Paul S. to sort a table with ASC and DESC order
 * with the <thead> and <tbody> structure easily.
 * 
 * https://stackoverflow.com/a/14268260/4241030
 */
var TableSorter = {
    makeSortable: function(table){
        // Store context of this in the object
        var _this = this;
        var th = table.tHead, i;
        th && (th = th.rows[0]) && (th = th.cells);

        if (th){
            i = th.length;
        }else{
            return; // if no `<thead>` then do nothing
        }

        // Loop through every <th> inside the header
        while (--i >= 0) (function (i) {
            var dir = 1;

            // Append click listener to sort
            th[i].addEventListener('click', function () {
                _this._sort(table, i, (dir = 1 - dir));
            });
        }(i));
    }, _sort: function (table, col, reverse) {
        var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
        tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
        i;

        reverse = -((+reverse) || -1);

        // Sort rows
        tr = tr.sort(function (a, b) {
            // `-1 *` if want opposite order
            return reverse * (
                // Using `.textContent.trim()` for test
                a.cells[col].textContent.trim().localeCompare(
                    b.cells[col].textContent.trim()
                )
            );
        });

        for(i = 0; i < tr.length; ++i){
            // Append rows in new order
            tb.appendChild(tr[i]);
        }
    }
};

可以如以下示例所示使用该方法:

window.onload = function(){
    TableSorter.makeSortable(document.getElementById("myTable"));
};

用jQuery排序表

使用jQuery的过程几乎相同, 但是我们可以使用某些实用程序(例如find方法)在表中查找第th个元素。然后, 我们将对每个这些元素附加一个侦听器, 并添加使用localeCompare和jQuery的isNumber实用程序的排序器:

/**
 * mini jQuery plugin based on the answer by Nick Grealy
 * 
 * https://stackoverflow.com/a/19947532/4241030
 */
(function($){
	$.fn.extend({
        makeSortable: function(){
            var MyTable = this;

            var getCellValue = function (row, index){ 
                return $(row).children('td').eq(index).text();
            };
            
            MyTable.find('th').click(function(){
                var table = $(this).parents('table').eq(0);
            
                // Sort by the given filter
                var rows = table.find('tr:gt(0)').toArray().sort(function(a, b) {
                    var index = $(this).index();
                    var valA = getCellValue(a, index), valB = getCellValue(b, index);
            
                    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
                });
            
                this.asc = !this.asc;
            
                if (!this.asc){
                    rows = rows.reverse();
                }
            
                for (var i = 0; i < rows.length; i++){
                    table.append(rows[i]);
                }
            });
        }
    });
})(jQuery);

可以像这样使用:

$(function(){
	$("#myTable").makeSortable();
});

在给出的2个示例使用jQuery或VanillaJS对表进行排序之后, 你肯定会看到在这两个示例中如何使用localeCompare。 localeCompare()方法返回一个数字, 该数字指示参考字符串是按排序顺序位于给定字符串之前还是之后还是与之相同。此函数在JavaScript引擎的String原型中。

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何使用纯JavaScript或jQuery在客户端对表进行排序

评论 抢沙发

评论前必须登录!