jQuery table sort

后端 未结 15 2660
温柔的废话
温柔的废话 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

    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;
            }
    
    
    idnameage
    1Julian31
    2Bert12
    3Xavier25
    4Mindy32
    5David40

    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

提交回复
热议问题