jQuery table sort

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

    If you want to avoid all the bells and whistles then may I suggest this simple sortElements plugin. Usage:

    var table = $('table');
    
    $('.sortable th')
        .wrapInner('')
        .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;
    
            });
    
        });
    

    And a demo. (click the "city" and "facility" column-headers to sort)

提交回复
热议问题