jQuery按一个td的值对表行进行排序

  • 本文关键字:排序 td 一个 jQuery 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/

为了拥有一个有效的表,您应该用thead元素包装第一个tr,用tbody元素包装其他tr。对于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 + '.';
});

请参阅此更新的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');
    });
});

最新更新