我有一个非常简单的HTML表,有4列:

Facility Name, Phone #, City, Specialty

我希望用户只能按设施名称和城市进行排序。

我如何使用jQuery编码这个?


当前回答

这一个不会挂起浏览器,容易配置进一步:

var table = $('table');

$('th.sortable').click(function(){
    var table = $(this).parents('table').eq(0);
    var ths = table.find('tr:gt(0)').toArray().sort(compare($(this).index()));
    this.asc = !this.asc;
    if (!this.asc)
       ths = ths.reverse();
    for (var i = 0; i < ths.length; i++)
       table.append(ths[i]);
});

function compare(idx) {
    return function(a, b) {
       var A = tableCell(a, idx), B = tableCell(b, idx)
       return $.isNumeric(A) && $.isNumeric(B) ? 
          A - B : A.toString().localeCompare(B)
    }
}

function tableCell(tr, index){ 
    return $(tr).children('td').eq(index).text() 
}

其他回答

我们刚刚开始使用这个灵巧的工具:https://plugins.jquery.com/tablesorter/

有一个关于它的使用的视频: http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx

    $('#tableRoster').tablesorter({
        headers: {
            0: { sorter: false },
            4: { sorter: false }
        }
    });

用一个简单的表格

<table id="tableRoster">
        <thead> 
                  <tr>
                    <th><input type="checkbox" class="rCheckBox" value="all" id="rAll" ></th>
                    <th>User</th>
                    <th>Verified</th>
                    <th>Recently Accessed</th>
                    <th>&nbsp;</th>
                  </tr>
        </thead>

到目前为止,我使用过的最简单的方法是:http://datatables.net/

令人惊讶的是简单的……只是确保如果你走DOM替换路线(IE,建立一个表,让DataTables重新格式化它),然后确保用<thead>和<tbody>格式化你的表,否则它将不起作用。这是唯一的问题。

它还支持AJAX等。就像所有真正优秀的代码一样,关闭它也非常容易。不过,你会对你用的东西感到惊讶的。我从一个只对一个字段进行排序的“裸”DataTable开始,然后意识到一些特性确实与我正在做的事情相关。客户喜欢这些新功能。

加分到数据表的完整ThemeRoller支持....

我在tablesorter上也有不错的运气,但它远没有那么简单,没有那么好的文档,而且只有一般的功能。

根据James的回答,我只改变排序函数,使其更通用。这样它将按字母顺序和数字进行排序。

if( $.text([a]) == $.text([b]) )
    return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
    return $.text([a]) > $.text([b]) ? 
       inverse ? -1 : 1
       : inverse ? 1 : -1;
}
else{
    return parseInt($.text([a])) > parseInt($.text([b])) ? 
      inverse ? -1 : 1
      : inverse ? 1 : -1;
}

我最终使用了尼克的答案(最受欢迎但不被接受)https://stackoverflow.com/a/19947532/5271220

并将其与https://stackoverflow.com/a/16819442/5271220结合起来,但不想在项目中添加图标或fontawesome。对于sort-column-asc/desc的CSS样式,我设置了颜色、填充、圆角边框。

我还修改了它,按类而不是按任何,这样我们就可以控制哪些是可排序的。如果以后有两个表,这也可以派上用场,尽管需要为此做更多的修改。

身体:

 html += "<thead>\n";
    html += "<th></th>\n";
    html += "<th class=\"sort-header\">Name <span></span></i></th>\n";
    html += "<th class=\"sort-header\">Status <span></span></th>\n";
    html += "<th class=\"sort-header\">Comments <span></span></th>\n";
    html += "<th class=\"sort-header\">Location <span></span></th>\n";
    html += "<th nowrap class=\"sort-header\">Est. return <span></span></th>\n";
    html += "</thead>\n";
    html += "<tbody>\n"; ...

... 再往下看

$("body").on("click", ".sort-header", function (e) {
    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc) { rows = rows.reverse() }
    for (var i = 0; i < rows.length; i++) { table.append(rows[i]) }

    setIcon(e.target, this.asc);
});

功能:

function comparer(index) {
        return function (a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index)
            return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
        }
    }

    function getCellValue(row, index) {
        return $(row).children('td').eq(index).text()
    }

    function setIcon(element, inverse) {

        var iconSpan = $(element).find('span');

        if (inverse == true) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-asc');
            $(iconSpan)[0].innerHTML = " &#8593 " // arrow up
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-desc');
            $(iconSpan)[0].innerHTML = " &#8595 " // arrow down 
        }

        $(element).siblings().find('span').each(function (i, obj) {
            $(obj).removeClass();
            obj.innerHTML = "";
        });
    }

另一种对HTML表进行排序的方法。(基于W3.JS HTML Sort)

/* Facility Name */ $('#bioTable th:eq(0)').addClass("control-label pointer"); /* Phone # */ $('#bioTable th:eq(1)').addClass("not-allowed"); /* City */ $('#bioTable th:eq(2)').addClass("control-label pointer"); /* Specialty */ $('#bioTable th:eq(3)').addClass("not-allowed"); var collection = [{ "FacilityName": "MinION", "Phone": "999-8888", "City": "France", "Specialty": "Genetic Prediction" }, { "FacilityName": "GridION X5", "Phone": "999-8812", "City": "Singapore", "Specialty": "DNA Assembly" }, { "FacilityName": "PromethION", "Phone": "929-8888", "City": "San Francisco", "Specialty": "DNA Testing" }, { "FacilityName": "iSeq 100 System", "Phone": "999-8008", "City": "Christchurch", "Specialty": "gDNA-mRNA sequencing" }] $tbody = $("#bioTable").append('<tbody></tbody>'); for (var i = 0; i < collection.length; i++) { $tbody = $tbody.append('<tr class="item"><td>' + collection[i]["FacilityName"] + '</td><td>' + collection[i]["Phone"] + '</td><td>' + collection[i]["City"] + '</td><td>' + collection[i]["Specialty"] + '</td></tr>'); } .control-label:after { content: "*"; color: red; } .pointer { cursor: pointer; } .not-allowed { cursor: not-allowed; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://www.w3schools.com/lib/w3.js"></script> <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" /> <p>Click the <strong>table headers</strong> to sort the table accordingly:</p> <table id="bioTable" class="w3-table-all"> <thead> <tr> <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(1)')">Facility Name</th> <th>Phone #</th> <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(3)')">City</th> <th>Specialty</th> </tr> </thead> </table>