简体   繁体   中英

jQuery sort custom table

I'm working on a small userscript to sort a table, the structure of the table is really weird however. What i'm trying to do is to add an extra sort feature so I can sort on the ranking (#) of the persons.

Table data looks like this:

<table id="outer">
    <tr>
        <td><div id="bgn"></div></td>
        <td><a href="#">User 1</a></td>
        <td>
            <table id="inner">
                <tbody>
                    <tr>
                        <td>Rank</td>
                        <td id="tdp">#28</td>
                    </tr>
                </tbody>
            </table>
        </td>
    </tr>
    <!-- more rows -->
</table>

There are some additional <td> 's but they are not important right now. There are about 52 rows, but these could vary, of course.

Current jQuery code I have:

jQuery( document ).ready(function() {
    var rankings = [];

    $(document).on('click', '#tdr', function() {
    // skipping first line because it's the header

    $('tr:not(:first-child').each(function () {
        var rank = $(this).find('#tdp').text();
        var rank2 = rank.substring(1, rank.length)
        rankings.push(rank2);
    });

        console.log(rankings.sort(sortNumber));
    });

    function sortNumber(num1, num2) {
        return num1 - num2;
    }
});

JS Bin Example

The output in the console is a correctly sorted array with all the rankings, I just don't have any idea how to also swap the corresponding <tr> 's so that the table get's rebuild the right way. Looking for any tips or pointers!

This suggestion is not really into "sorting" the rows, but re-constructing the table with the sorted rows. But this should do the job:

rankings = rankings.sort(sortNumber);
var table = $('<table></table>');
for (var i = 0; i < rankings.length; i++) {
  var row = $('tr').filter(function() {
    var rank = $(this).find('#tdp').text();
    return rank.substring(1, rank.length) == i;
  });
  table.append(row);
}
$('#originalTable').html(table.html());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM