jQuery排序表行的值为一个td

时间:2015-03-20 13:51:13

标签: jquery

您如何按我拥有的pts课程对此表格进行排序:

<table>
    <tr>
        <th>rank</th>
        <th>team</th>
        <th>pts</th>
    </tr>
    <tr>
        <td>1.</td>
        <td>Chelsea</td>
        <td class="pts">3</td>
    </tr>
    <tr>
        <td>2.</td>
        <td>Arsenal</td>
        <td class="pts">1</td>
    </tr>
    <tr>
        <td>3.</td>
        <td>Man U</td>
        <td class="pts">2</td>
    </tr>
</table>

<button>SORT</button>

代码: http://jsfiddle.net/dxL8b2k0/

2 个答案:

答案 0 :(得分:4)

要拥有有效的表,您应该将第一个tr包含thead元素,将其他tr包含tbody个元素。要对tr进行排序,您可以使用sort方法:

$('tbody > tr').sort(function (a, b) {
    return +$('td.pts', b).text() > +$('td.pts', a).text();
}).appendTo('tbody');

要更新排名单元格,您可以使用text方法:

$('tbody > tr').sort(function (a, b) {
    return +$('td.pts', b).text() > +$('td.pts', a).text();
}).appendTo('tbody').find('td:first').text(function(index) {
    return ++index + '.';
});

答案 1 :(得分:3)

有关正常工作的版本,请参阅此更新的fiddle

$('#btnGo').on('click', function () {
    // get rows as array and detach them from the table
    var rows = $('#tbl tr:not(:first)').detach();

    // sort rows by the number in the td with class "pts"
    rows.sort(function (row1, row2) {
        return parseInt($(row1).find('td.pts').text()) - parseInt($(row2).find('td.pts').text());
    });

    // add each row back to the table in the sorted order (and update the rank)
    var rank = 1;
    rows.each(function () {
        $(this).find('td:first').text(rank + '.');
        rank++;
        $(this).appendTo('#tbl');
    });
});