问题
Very similair to this question: Sort table rows based on their Class Names
Consider the following table:
<table>
<thead>
<th>A column</th>
</thead>
<tbody>
<tr>
<td class="x">A</td>
</tr>
<tr>
<td class="c">B</td>
</tr>
<tr>
<td class="">C</td>
</tr>
</tbody>
</table>
I would like to sort rows based on the first (in this case only) column class name. Some td
don't have a class specified. So the desired effect would be: A-B-C -> C-B-A or B-A-C
(I don't care where the classless tds are placed). I know I can get class with jquery, for example:
$(table tr).eq(1).find('td').eq(0).attr('class')
Any ideas?
回答1:
Use sort() to sorting array of tr
elements. You can get class of element in function of sort and set arrangement of every element.
$("table tbody tr").sort(function (a, b){
return $("td", b).attr("class") < $("td", a).attr("class") ? 1 : -1;
}).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>A column</th>
</thead>
<tbody>
<tr>
<td class="x">A</td>
</tr>
<tr>
<td class="c">B</td>
</tr>
<tr>
<td class="">C</td>
</tr>
</tbody>
</table>
来源:https://stackoverflow.com/questions/38352546/sorting-table-rows-based-on-column-class-names-using-jquery