使用jQuery根据列类名称对表行进行排序 [英] Sorting table rows based on column class names using jquery

查看:58
本文介绍了使用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>

我想根据第一个(仅在这种情况下)列类名称对行进行排序.某些 td 没有指定类.因此,所需的效果将是: A-B-C->C-B-A或B-A-C (我不在乎无类tds放在何处).我知道我可以使用jquery取得课程,例如:

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')

有什么想法吗?

推荐答案

使用

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>

这篇关于使用jQuery根据列类名称对表行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆