jQuery-向表添加一行后对表进行排序 [英] jQuery - sort a table after adding a row to it

查看:89
本文介绍了jQuery-向表添加一行后对表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表,一个表有2列,另一个表有1列.当您单击一行时,该行将从表中删除,并且新TR将添加到相反表的末尾.现在,我想按字母顺序对其进行排序.

I have 2 tables, one table has 2 columns, the other table has 1 column. When you click on a row, that row is removed from the table and a new TR is added to the end of the opposite table. Now I want to sort it alphabetically.

像tablesorter这样的jQuery插件对于我想做的事情来说是完全过头了.有一种简单的方法可以对表格进行排序吗?

jQuery plugins like tablesorter are total overkill for what I want to do. Is there a simple way I can sort the table?

小提琴

推荐答案

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

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

<table id="sort-table">
    <tbody>
        <tr><td>he</td></tr>
        <tr><td>stackoverflow</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
    });
});

这篇关于jQuery-向表添加一行后对表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆