jQuery table sort

后端 未结 15 2657
温柔的废话
温柔的废话 2020-11-22 09:00

I have a very simple HTML table with 4 columns:

Facility Name, Phone #, City, Specialty

I want the user to be able to sort by Faci

相关标签:
15条回答
  • 2020-11-22 09:44

    My answer would be "be careful". A lot of jQuery table-sorting add-ons only sort what you pass to the browser. In many cases, you have to keep in mind that tables are dynamic sets of data, and could potentially contain zillions of lines of data.

    You do mention that you only have 4 columns, but much more importantly, you don't mention how many rows we're talking about here.

    If you pass 5000 lines to the browser from the database, knowing that the actual database-table contains 100,000 rows, my question is: what's the point in making the table sortable? In order to do a proper sort, you'd have to send the query back to the database, and let the database (a tool actually designed to sort data) do the sorting for you.

    In direct answer to your question though, the best sorting add-on I've come across is Ingrid. There are many reasons that I don't like this add-on ("unnecessary bells and whistles..." as you call it), but one of it's best features in terms of sort, is that it uses ajax, and doesn't assume that you've already passed it all the data before it does its sort.

    I recognise that this answer is probably overkill (and over 2 years late) for your requirements, but I do get annoyed when developers in my field overlook this point. So I hope someone else picks up on it.

    I feel better now.

    0 讨论(0)
  • 2020-11-22 09:44

    This is a nice way of sorting a table:

    $(document).ready(function () {
                    $('th').each(function (col) {
                        $(this).hover(
                                function () {
                                    $(this).addClass('focus');
                                },
                                function () {
                                    $(this).removeClass('focus');
                                }
                        );
                        $(this).click(function () {
                            if ($(this).is('.asc')) {
                                $(this).removeClass('asc');
                                $(this).addClass('desc selected');
                                sortOrder = -1;
                            } else {
                                $(this).addClass('asc selected');
                                $(this).removeClass('desc');
                                sortOrder = 1;
                            }
                            $(this).siblings().removeClass('asc selected');
                            $(this).siblings().removeClass('desc selected');
                            var arrData = $('table').find('tbody >tr:has(td)').get();
                            arrData.sort(function (a, b) {
                                var val1 = $(a).children('td').eq(col).text().toUpperCase();
                                var val2 = $(b).children('td').eq(col).text().toUpperCase();
                                if ($.isNumeric(val1) && $.isNumeric(val2))
                                    return sortOrder == 1 ? val1 - val2 : val2 - val1;
                                else
                                    return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
                            });
                            $.each(arrData, function (index, row) {
                                $('tbody').append(row);
                            });
                        });
                    });
                });
                table, th, td {
                border: 1px solid black;
            }
            th {
                cursor: pointer;
            }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
            <tr><th>id</th><th>name</th><th>age</th></tr>
            <tr><td>1</td><td>Julian</td><td>31</td></tr>
            <tr><td>2</td><td>Bert</td><td>12</td></tr>
            <tr><td>3</td><td>Xavier</td><td>25</td></tr>
            <tr><td>4</td><td>Mindy</td><td>32</td></tr>
            <tr><td>5</td><td>David</td><td>40</td></tr>
        </table>

    The fiddle can be found here:
    https://jsfiddle.net/e3s84Luw/

    The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code

    0 讨论(0)
  • 2020-11-22 09:46

    @Nick Grealy's answer is great, but it does not take into account possible rowspan attributes of the table header cells (and probably the other answers don't do it either). Here is an improvement of the @Nick Grealy's answer which fixes that. Based on this answer too (thanks @Andrew Orlov).

    I've also replaced the $.isNumeric function with a custom one (thanks @zad) to make it work with older jQuery versions.

    To activate it, add class="sortable" to the <table> tag.

    $(document).ready(function() {
    
        $('table.sortable th').click(function(){
            var table = $(this).parents('table').eq(0);
            var column_index = get_column_index(this);
            var rows = table.find('tbody tr').toArray().sort(comparer(column_index));
            this.asc = !this.asc;
            if (!this.asc){rows = rows.reverse()};
            for (var i = 0; i < rows.length; i++){table.append(rows[i])};
        })
    
    });
    
    function comparer(index) {
        return function(a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index);
            return isNumber(valA) && isNumber(valB) ? valA - valB : valA.localeCompare(valB);
        }
    }
    function getCellValue(row, index){ return $(row).children('td').eq(index).html() };
    
    function isNumber(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    
    function get_column_index(element) {
        var clickedEl = $(element);
        var myCol = clickedEl.closest("th").index();
        var myRow = clickedEl.closest("tr").index();
        var rowspans = $("th[rowspan]");
        rowspans.each(function () {
            var rs = $(this);
            var rsIndex = rs.closest("tr").index();
            var rsQuantity = parseInt(rs.attr("rowspan"));
            if (myRow > rsIndex && myRow <= rsIndex + rsQuantity - 1) {
                myCol++;
            }
        });
        // alert('Row: ' + myRow + ', Column: ' + myCol);
        return myCol;
    };
    
    0 讨论(0)
  • 2020-11-22 09:50

    By far, the easiest one I've used is: http://datatables.net/

    Amazingly simple...just make sure if you go the DOM replacement route (IE, building a table and letting DataTables reformat it) then make sure to format your table with <thead> and <tbody> or it won't work. That's about the only gotcha.

    There's also support for AJAX, etc. As with all really good pieces of code, it's also VERY easy to turn it all off. You'd be suprised what you might use, though. I started with a "bare" DataTable that only sorted one field and then realized that some of the features were really relevant to what I'm doing. Clients LOVE the new features.

    Bonus points to DataTables for full ThemeRoller support....

    I've also had ok luck with tablesorter, but it's not nearly as easy, not quite as well documented, and has only ok features.

    0 讨论(0)
  • 2020-11-22 09:51

    I love this accepted answer, however, rarely do you get requirements to sort html and not have to add icons indicating the sorting direction. I took the accept answer's usage example and fixed that quickly by simply adding bootstrap to my project, and adding the following code:

    <div></div>

    inside each <th> so that you have a place to set the icon.

    setIcon(this, inverse);

    from the accepted answer's Usage, below the line:

    th.click(function () {

    and by adding the setIcon method:

    function setIcon(element, inverse) {
    
            var iconSpan = $(element).find('div');
    
            if (inverse == false) {
                $(iconSpan).removeClass();
                $(iconSpan).addClass('icon-white icon-arrow-up');
            } else {
                $(iconSpan).removeClass();
                $(iconSpan).addClass('icon-white icon-arrow-down');
            }
            $(element).siblings().find('div').removeClass();
        }
    

    Here is a demo. --You need to either run the demo in Firefox or IE, or disable Chrome's MIME-type checking for the demo to work. It depends on the sortElements Plugin, linked by the accepted answer, as an external resource. Just a heads up!

    0 讨论(0)
  • 2020-11-22 09:52

    This one does not hang up the browser/s, easy configurable further:

    var table = $('table');
    
    $('th.sortable').click(function(){
        var table = $(this).parents('table').eq(0);
        var ths = table.find('tr:gt(0)').toArray().sort(compare($(this).index()));
        this.asc = !this.asc;
        if (!this.asc)
           ths = ths.reverse();
        for (var i = 0; i < ths.length; i++)
           table.append(ths[i]);
    });
    
    function compare(idx) {
        return function(a, b) {
           var A = tableCell(a, idx), B = tableCell(b, idx)
           return $.isNumeric(A) && $.isNumeric(B) ? 
              A - B : A.toString().localeCompare(B)
        }
    }
    
    function tableCell(tr, index){ 
        return $(tr).children('td').eq(index).text() 
    }
    
    0 讨论(0)
提交回复
热议问题