简体   繁体   English

使用jquery基于列类名对表行进行排序

[英]Sorting table rows based on column class names using jquery

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. 有些td没有指定类。 So the desired effect would be: ABC -> CBA or BAC (I don't care where the classless tds are placed). 所以期望的效果是: ABC -> CBA or BAC (我不关心无类别的tds放在哪里)。 I know I can get class with jquery, for example: 我知道我可以用jquery来上课,例如:

$(table tr).eq(1).find('td').eq(0).attr('class')

Any ideas? 有任何想法吗?

Use sort() to sorting array of tr elements. 使用sort()来排序tr元素的数组。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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