jQuery table sort

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

    I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.

    • Works in Chrome, Firefox, Opera AND IE(8)
    • Only uses JQuery
    • Does alpha and numeric sorting - ascending and descending

    $('th').click(function(){
        var table = $(this).parents('table').eq(0)
        var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).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 $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
        }
    }
    function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
    table, th, td {
        border: 1px solid black;
    }
    th {
        cursor: pointer;
    }
    
    
    CountryDateSize
    France2001-01-0125
    spain2005-05-05
    Lebanon2002-02-02-17
    Argentina2005-04-04100
    USA-6

    ** Update: 2018

    • For those that are interested, I've provided an ES6 Plain Javascript solution here.

提交回复
热议问题