且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery-向表添加一行后对表进行排序

更新时间:2023-02-02 17:41:37

在这里,您有一个带有小提琴演示在这里:

Here you have a simple table sorter with a Fiddle demo here:

<table id="sort-table">
    <tbody>
        <tr><td>he</td></tr>
        <tr><td>***</td></tr>
        <tr><td>by</td></tr>
        <tr><td>vote</td></tr>
        <tr><td>post</td></tr>
        <tr><td>And</td></tr>
        <tr><td>clicking</td></tr>
        <tr><td>up</td></tr>
        <tr><td>did</td></tr>
    </tbody>
</table>
<br>
<button class="sort-table asc">sort ASC</button>
<button class="sort-table desc">sort DESC</button>

JQUERY

$('.sort-table').click(function(e) {
    e.preventDefault();                    // prevent default behaviour

    var sortAsc = $(this).hasClass('asc'), // ASC or DESC sorting
        $table  = $('#sort-table'),        // cache the target table DOM element
        $rows   = $('tbody > tr', $table); // cache rows from target table body

    $rows.sort(function(a, b) {

        var keyA = $('td',a).text();
        var keyB = $('td',b).text();

        if (sortAsc) {
            return (keyA > keyB) ? 1 : 0;  // A bigger than B, sorting ascending
        } else {
            return (keyA < keyB) ? 1 : 0;  // B bigger than A, sorting descending
        }
    });

    $rows.each(function(index, row){
      $table.append(row);                  // append rows after sort
    });
});