使用jQuery根据背景颜色对表行进行排序 [英] Sort table rows based on background-color using jquery

查看:70
本文介绍了使用jQuery根据背景颜色对表行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 FIDDLE

<table>
    <tr>
        <td>
            <div style="background:blue;color:white">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:pink;color:white">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:blue;color:white">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:green;color:white">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:pink;color:white">hello</div>
        </td>
    </tr>
     <tr>
        <td>
            <div style="background:green;color:white">hello</div>
        </td>
    </tr>
</table>

如何根据颜色重新排列html表行?我想根据行的背景颜色对html表行进行分组.

How do i rearrange the html table rows based on color? I want to group html table rows based on the background color of the rows.

推荐答案

使用

Use sort() to sorting array of tr elements. You can get backgroud-color of element in function of sort and set arrangement of every element.

$("table tr").sort(function (a, b){
    return $("div", b).css("background") < $("div", a).css("background") ? 1 : -1;    
}).appendTo('table');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>
            <div style="background:blue">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:pink">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:blue">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:green">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:pink">hello</div>
        </td>
    </tr>
    <tr>
        <td>
            <div style="background:green">hello</div>
        </td>
    </tr>
</table>

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

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