排序html表列客户端没有第三方以外的jquery

Sorting html table columns client side without third party other than jquery

本文关键字:第三方 jquery html 客户端 排序      更新时间:2023-09-26

我通过jQuery ajax调用web api服务获取数据。我不想发送请求,让服务器端按asc/desc按每列排序所以我想做的是客户端HTML表排序

我在整个项目中一直使用jQuery和Javascript,但我真的更喜欢不使用第三方工具,如jqgrid或datatable.net

我有什么选择?

在数据被输出到html表格行之前,我已经在Javascript中保存了数据因此,有一个click事件选项可以对。each循环中的数据进行排序

jQuery Javascript/

function writeResponses(allData) {
var strResult = "<table id='headerTable' class='table'><thead id='headers'><th>ID</th><th>Location</th><th>Comment</th><th>Additional Information</th><th>Date Reported</th><th>TC Key</th>";
strResult += "<th>Loc Acct Num</th><th>TC Date</th><th>WorkedID</th><th>TC Type</th><th>Corrected TC Type</th></thead>";
$.each(allData, function (index, issues) {
    strResult += "<tr><td>" + issues.DOCCCOIssuesId + "</td><td> " + issues.Location + "</td><td>" + issues.Comment + "</td>";
    strResult += "<td>" + issues.AdditionalInformation + "</td><td>" + issues.DateReported + "</td><td>" + issues.TCKey + "</td>";
    strResult += "<td>" + issues.LocAcctNum + "</td><td>" + issues.TCDate + "</td><td>" + issues.WorkedByNTID + "</td>";
    strResult += "<td>"+issues.TCType+"</td><td>"+issues.CorrectedTCType+"</td></tr>";
});
strResult += "</table>";
$("#divResult").html(strResult);
}

生成的html表

<table id="headerTable" class="table">
<thead id="headers">
<tr>
    <th>ID</th><th>Location</th><th>Comment</th>
</tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>CCO</td>
        <td>Compliment</td>
    </tr>
    <tr>
        <td>2</td>
        <td>afafd</td>
        <td>oafaf</td>
    </tr>
    </tbody>

您可以在收到数据时对其进行初始排序。allData似乎是一个数组,所以你可以这样做:

allData.sort(function(a, b){
    if(a.DOCCCOIssuesId < b.DOCCCOIssuesId ) return -1;
    if(a.DOCCCOIssuesId > b.DOCCCOIssuesId ) return 1;
    // other sort keys?
    return 0;
});

如果你想要有可点击的排序列,下面的例子可能会有帮助:

jQuery("table.stats").each(function() {
    var $ = jQuery;
    var tbl = $(this);
    $('th', this).click(function() {
        var clickRow = $(this).closest('tr');
        var body = $(this).closest('tbody').get(0);
        var col = $(this).index();
        var sortKeys = $(body).find('tr').not(clickRow).map(function(idx, row) {
            return {
                row: row,
                key: $('td', row).eq(col).text() // you can do all sorts of things besides simple text values. cache the key for efficiency
            };
        }).get();
        sortKeys.sort(function(a, b) {
            return a.key > b.key ? 1 : a.key < b.key ? -1 : 0; 
        });
        for (var i = sortKeys.length - 1; i >= 0; i--) {
            body.appendChild(sortKeys[i].row);
        }
    });
});