Jquery sort table data

前端 未结 7 2192
醉酒成梦
醉酒成梦 2020-12-14 00:50

I got struck in sorting tds in table using jquery.

My Demo fiddle

How can I call it for any table with id in my project?

var $sort = this;
v         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 01:50

    I think you are missing the final "reset" function to sort the table. The desc code will not work because the order must be switched.

    Code:

    $('.sort').click(function (e) {
        var $sort = this;
        var $table = $('#mytable');
        var $rows = $('tbody > tr', $table);
        $rows.sort(function (a, b) {
            var keyA = $('td', a).text();
            var keyB = $('td', b).text();
            if ($($sort).hasClass('asc')) {
                return (keyA > keyB) ? 1 : 0;
            } else {
                return (keyA > keyB) ? 0 : 1;
            }
        });
        $.each($rows, function (index, row) {
            $table.append(row);
        });
        e.preventDefault();
    });
    

    Demo: http://jsfiddle.net/7wwvL/

    UPDATE

    More in general your function can be:

    function sortTable($table,order){
        var $rows = $('tbody > tr', $table);
        $rows.sort(function (a, b) {
            var keyA = $('td', a).text();
            var keyB = $('td', b).text();
            if (order=='asc') {
                return (keyA > keyB) ? 1 : 0;
            } else {
                return (keyA > keyB) ? 0 : 1;
            }
        });
        $.each($rows, function (index, row) {
            $table.append(row);
        });
    }
    
    sortTable($('#mytable'),'asc')
    

    Demo: http://jsfiddle.net/d7Kbx/

提交回复
热议问题