Jquery sort table data

前端 未结 7 2191
醉酒成梦
醉酒成梦 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:47

    Here is a modified version of the answer from Adeneo. This will sort the table based on the text in the specified column instead of only the first column. This will also look for the word "Name" in the second column and make sure that row stays on top (header row).

    function SortTable(table, order, nr) {
    var asc = order === 'asc',
        tbody = table.find('tbody');
    
    tbody.find('tr').sort(function (a, b) {
        if ($('td:nth-child('+ nr +')', a).text() == "Name") return $('td:nth-child('+ nr +')', a).text();
        else if (asc) {
            return $('td:nth-child('+ nr +')', a).text().localeCompare($('td:nth-child('+ nr +')', b).text());
        } else {
            return $('td:nth-child('+ nr +')', b).text().localeCompare($('td:nth-child('+ nr +')', a).text());
        }
    }).appendTo(tbody);}
    

提交回复
热议问题