How to sort one column via several ways in a header?

前端 未结 2 1563
死守一世寂寞
死守一世寂寞 2020-12-04 00:16

I have the tablesorter from motti and I can\'t find out a simple way to sort a certain column in more than one way from 2 different hot areas in the same header. (One way vi

2条回答
  •  隐瞒了意图╮
    2020-12-04 01:19

    The way the text extraction works is that it is only used when the table is initialized or updated. It's not really meant to sort two different blocks of information within the same cell, but it would be possible to use it to format the text a certain way, then use the textSorter option to sort the desired part (demo):

    $(function () {
    
        var $cell;
        $('#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) {
                var x = a.split(';'),
                    y = b.split(';'),
                    i = $cell && $cell.is('.active') ? 1 : 0;
                return $.tablesorter.sortNatural($.trim(x[i]), $.trim(y[i]));
            },
            initialized: function () {
                $cell = $('#games').find('.percSort');
    
                // trigger sort here because any initial sort using sortList
                // won't have the $cell variable defined, so it defaults to name
                $('#games').trigger('sorton', [ [[1,1]] ]);
    
                $cell.click(function () {
                    // activate percentage sort
                    $cell.addClass('active');
                    return false;
                }).closest('th').click(function () {
                    // clicking on header outside of percSort
                    // inactivates the percentage sort
                    $cell.removeClass('active');
                });
    
            }
        });
    
    });
    

    Updates:

    • To make sure the column doesn't get detected to only use a percent parser, set the sorter type in the header:

      Game...
      
    • To make the table initially sort the percent, you need to do two things:

      • Add the "active" class to the cell  66% 

      • Add $('#games').trigger('sorton', [ [[1,1]] ]); because the $cell variable isn't defined until after tablesorter has initialized. And you can't define it before because the headers are rebuilt during initialization. Code added to the example above.

提交回复
热议问题