Jquery Sort multiple Tbody

社会主义新天地 提交于 2019-12-23 04:45:39

问题


I have a table like this :

<table>
    <thead>
        <tr>
            <th>Department</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Data</th>
            <th>100</th>
        </tr>
        <tr>
            <td>DTP</td>
            <td>20</td>
        </tr>
        <tr>
            <td>VTP</td>
            <td>30</td>
        </tr>
        <tr>
            <td>RTP</td>
            <td>50</td>
        </tr>
    </tbody>
    <tbody>
        <tr>
            <th>Testing</th>
            <th>100</th>
        </tr>
        <tr>
            <td>QTP</td>
            <td>20</td>
        </tr>
        <tr>
            <td>ATP</td>
            <td>30</td>
        </tr>
        <tr>
            <td>CTP</td>
            <td>50</td>
        </tr>
    </tbody>
</table>

When I click department header, tr inside data and testing should get sorted. But data and testing TH should remain the same.

I don't want to use any jQuery plugin. Kindly share code to do this task.


回答1:


Here is a quick implementation. Hopefully you will improve it and it will match your needs:

var $table = $('table'),
    $th = $table.find('thead th'),
    $tbody = $table.find('tbody');

$th.on('click', function() {

    $th.removeClass();

    var index = this.cellIndex,
        sortType = $(this).data('sort'),
        sortDir  = $(this).data('dir') || 'asc';

    $tbody.each(function() {
        $(this).find('tr').slice(1).sort(function(a, b) {

            var aText = $(a).find('td:eq(' + index + ')').text(),
                bText = $(b).find('td:eq(' + index + ')').text();

            if (sortDir == 'desc') {
                temp = aText;
                aText = bText;
                bText = temp;
            }

            if (sortType == 'string') {
                return aText.localeCompare(bText);    
            }
            else {
                return +aText - +bText;
            }
        })
        .appendTo(this);
    });

    $(this).data('dir', sortDir == 'asc' ? 'desc' : 'asc');
    $(this).removeClass().addClass('sort-' + sortDir);
});

Demo: http://jsfiddle.net/6uzVn/



来源:https://stackoverflow.com/questions/24030253/jquery-sort-multiple-tbody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!