jquery tablesorter : determining sort order for column

淺唱寂寞╮ 提交于 2019-12-02 11:21:13

问题


Is it possible for http://tablesorter.com to sort on different values depending on whether the sort is ascending or descending ?

I see how to return sort values for a cell based on arbitrary data with a parser (i.e.: http://code-cocktail.in/hidden-value-sorting-in-jquery-tablesorter-plugin/ ) , so returning different values in different situations seems simple enough.

The bit I'm banging my head on is that I cannot seem to determine the sort order when parsing. It looks like I can re-parse cells when a sort is being requested via the following:

 $(".tablesorter").bind("sortStart",function() { 
        $(".tablesorter").trigger("update");
 });

... however it looks like at the "sortStart" point the order of the sort isn't known, so the parser cannot provide different values based on that column's sort order.

Is this possible ? Thanks :-)


回答1:


For the following code to work, you'll need to use my fork of tablesorter which has css, widgets and addons that are not compatible with the original version.


This is somewhat similar to this Stackoverflow question except that it allows sorting one column using two different values (both answers work nicely using different methods).

A minor modification is required to use one value during ascending sort and another during descending sort (demo):

HTML (one cell)

<th class="gamename">
    <span class="name">Fun Fun</span>
    <span class="perc">96%</span>
</th>

Script

$(function () {

    $('#games').tablesorter({
        theme: 'blue',
        textExtraction: {
            0: function (node, table, cellIndex) {
                var $n = $(node);
                // add semi-colon between values
                return $n.find('.name').text() + ';' + $n.find('.perc').text();
            }
        },
        textSorter: function (a, b, direction, columnIndex, table) {
            if (columnIndex === 0) {
                var c = table.config,
                    x = a.split(';'),
                    y = b.split(';'),
                    // sort column by percentage when descending sort is active
                    i = c.$headers.eq(0).hasClass('tablesorter-headerDesc') ? 1 : 0;
                return $.tablesorter.sortNatural($.trim(x[i]), $.trim(y[i]));
            } else {
                return $.tablesorter.sortNatural(a,b);
            }
        }
    });

});


来源:https://stackoverflow.com/questions/27850608/jquery-tablesorter-determining-sort-order-for-column

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