小编典典

jQuery表格排序

all

我有一个非常简单的包含 4 列的 HTML 表格:

Facility Name, Phone #, City, Specialty

我希望用户能够仅按 设施名称城市 进行排序。

如何使用 jQuery 编写代码?


阅读 66

收藏
2022-07-06

共1个答案

小编典典

如果你想避免所有的花里胡哨,那么我可以推荐这个简单的sortElements插件。用法:

var table = $('table');

$('.sortable th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){

        var th = $(this),
            thIndex = th.index(),
            inverse = false;

        th.click(function(){

            table.find('td').filter(function(){

                return $(this).index() === thIndex;

            }).sortElements(function(a, b){

                if( $.text([a]) == $.text([b]) )
                    return 0;

                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;

            }, function(){

                // parentNode is the element we want to move
                return this.parentNode;

            });

            inverse = !inverse;

        });

    });

和一个演示。 (单击“城市”和“设施”列标题进行排序)

2022-07-06