Using jquery, how do you reorder rows in a table based on a TR attribute?

前端 未结 2 1042
野的像风
野的像风 2020-12-14 11:23

I have a table with rows similar to the following. These rows get updated from time to time via jquery calls. Using jquery, how would I construct a function that reorders th

2条回答
  •  被撕碎了的回忆
    2020-12-14 12:20

    Thanks, Kai. I have distilled the code a little while preserving clarity. Generally, you don't want to sort the thead or tfooter parts. So, it may be handy to just target only the elements in the tbody (although this was not in Chris' original question):

        var tb = $('tbody');
        var rows = tb.find('tr');
        rows.sort(function(a, b) {
            var keyA = $(a).attr('myAttribute');
            var keyB = $(b).attr('myAttribute');
            return keyA - keyB;
        });
        $.each(rows, function(index, row) {
            tb.append(row);
        });
    

    To sort in descending order, just reverse the return line as follows:

            return keyB - keyA;
    

提交回复
热议问题