Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

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

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 via "gamename" and another via "percentage".)
My code already sorts on Game on the gamename, but it does do the same when clicking on percentage (so the latter not by percentage, but by name).

What's the least-code way to do this? (Preferably with existing tablesorter options.)

Table header column:

<th>Game <span class="percSort">%</span></th>

Body column:

<th class="gamename">
<div style="width:66%;background-color: hsla(84,100%,50%,0.7);"></div>
<span class="name">Alphabetic</span>
<span class="perc">66%</span>
</th>

Domready code:

    $("#games")
    .tablesorter({
        sortList: [['.percSort',1]],
        textExtraction:{
            1:function(node, table, cellIndex) {
                return $(node).find('.name').text();
            },
            '.percSort':function(node, table, cellIndex) {
                return $(node).find('.perc').text();
            }
       }
    });

What I cannot do: split my corresponding column in more column. It displays colored bars via the css you can see.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not possible with an existing option as the tablesorter only allows you to set (and not change) a single sorting order for a column. There is however a workaround, which simply switches a custom parser off and on depending on where on the header you click:

Table header column:

<th id="thgame">Game <span class="percSort">%</span></th>

JavaScript:

// Add custom table parser for percentage.
$.tablesorter.addParser({
  id: 'perc',
  format: function(s, table, cell, cellIndex) {
    return $(cell).find('.perc').text().slice(0, -1);
  },
  type: 'numeric'
});

// Create tablesorter and disable default sorting for column.
$('#games').tablesorter({ ... });
$('#thgame').unbind();

// Create custom sorting events for column.
$('#thgame').click(function(){ 
    $('#thgame').removeClass('sorter-perc');
    $('#games').trigger('updateRows');
    $('#games').trigger('sorton', [ [[0,'n']] ]);
});
$('.percSort').click(function(e){ 
    $('#thgame').addClass('sorter-perc');
    $('#games').trigger('updateRows');
    $('#games').trigger('sorton', [ [[0,'n']] ]);
    e.stopPropagation() // prevent previous event from firing.
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...