Jquery sort table data

前端 未结 7 2193
醉酒成梦
醉酒成梦 2020-12-14 00:50

I got struck in sorting tds in table using jquery.

My Demo fiddle

How can I call it for any table with id in my project?

var $sort = this;
v         


        
7条回答
  •  抹茶落季
    2020-12-14 01:44

    Something like this

    function sortTable(table, order) {
        var asc   = order === 'asc',
            tbody = table.find('tbody');
    
        tbody.find('tr').sort(function(a, b) {
            if (asc) {
                return $('td:first', a).text().localeCompare($('td:first', b).text());
            } else {
                return $('td:first', b).text().localeCompare($('td:first', a).text());
            }
        }).appendTo(tbody);
    }
    

    could be called on any table like this

    sortTable($('#mytable'),'asc');
    

    FIDDLE

提交回复
热议问题