jQuery table sort

后端 未结 15 2808
温柔的废话
温柔的废话 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: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() 
    }
    

提交回复
热议问题