Sorting table rows based on column class names using jquery

点点圈 提交于 2021-01-06 08:59:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!