admin 发表于 2022-3-24 15:32:11

对表中的列进行排序

通过点击表格标题对表格列进行排序
<table width='100%' id='tblNotifications' style='display: none;' class='TFtable'><thead id='notitblhead'>
<tr>
<th id='thDate' onclick='sortNotifications(this);' title='Click to sort by Date' style='width: 100px;'>Date</th>
<th id='thType' onclick='sortNotifications(this);' title='Click to sort by Type'>Type</th>
<th id='thDoc' onclick='sortNotifications(this);' title='Click to sort by Document Type'>Doc Type</th>
<th id='thStatus' onclick='sortNotifications(this);' title='Click to sort by Status'>Status</th>
<th id='thProcess' onclick='sortNotifications(this);' title='Click to sort by Process'>Process</th>
<th style='width: 50px;'>Edit</th>
</tr>
</thead>
<tbody id='notifications'>
</tbody>
<tfoot></tfoot>
</table>

//javascript

var notinum = 1;

function sortNotifications(ele) {
        notinum *= -1;
        var sibling = prevAll(ele);
        var n = sibling.length;
        var fldtype = (ele.id == 'thDate') ? 'd' : ''; //use this line if a column is a date field where the year part is not the start of the string
        sortTableRows(notinum,n, fldtype);
}

function prevAll(element) {
    var result = [];

    while (element = element.previousElementSibling)
      result.push(element);
    return result;
}

function sortTableRows(f,n, fld=''){
        var rows = $('#tblNotifications tbodytr').get();

        rows.sort(function(a, b) {

                var A = getVal(a, fld);
                var B = getVal(b, fld);

                if(A < B) {
                        return -1*f;
                }
                if(A > B) {
                        return 1*f;
                }
                return 0;
        });

        function getVal(elm,fld=''){
                var v = $(elm).children('td').eq(n).text().toUpperCase();
                if(fld !=''){
                        v = getDateSortVal(v);
                }
                if($.isNumeric(v)){
                        v = parseInt(v,10);
                }
                return v;
        }
       
        function getDateSortVal(str){
                var sortdate = str.split("/");
                return sortdate+'/'+sortdate+'/'+sortdate;
        }

        $.each(rows, function(index, row) {
                $('#tblNotifications').children('tbody').append(row);
        });
}
页: [1]
查看完整版本: 对表中的列进行排序