首页 > 解决方案 > 如何根据标题对许多表重新排序?

问题描述

我想根据它们各自的标题按字母顺序对许多表进行重新排序。

例子 :

目前,我有:

  1. 带有“PHP”标题的表格

  2. 带有“Javascript”标题的表格

  3. 带有“Android”标题的表格

我想看看:

  1. 带有“Android”标题的表格

  2. 带有“Javascript”标题的表格

  3. 带有“PHP”标题的表格

我不知道该怎么做。

这是我的代码:

$('table').each(function() {
    $caption = $(this).find('>caption');
    $table = $(this);
    $table.sort(function (a, b) {
        var $a = $(a),
        $b = $(b),
        aVal = $a.find(">caption").text().toLowerCase(),
        bVal = $a.find(">caption").text().toLowerCase();
        if (aVal < bVal) return -1;
        else if (aVal > bVal) return 1;
        else return 0;
    });
    $('#results').append($table);
});

标签: javascriptjquerysortingtablesort

解决方案


在迭代它们时无法对表进行排序。

首先,您可以获得每个表格的标题,然后将其与其对应的表格分组并将其推入一个数组中。现在对数组进行排序并显示内容。

var tables = [];
$('table').each(function() {
    var caption = $(this).find('caption')[0];
    tables.push({
       'table' : $(this),
       'caption': $(caption).text().toLowerCase()
    });
});
tables.sort(function (tableA, tableB){
    if (tableA.caption < tableB.caption){
        return -1;
    }
    if (tableA.caption > tableB.caption){
        return 1;
    }
    return 0;
});

$.each( tables, function( index, tableObject){
    $('#results').append(tableObject.table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <caption>Zhp</caption> </table>
<table> <caption>php</caption> </table> 
<table> <caption>Javascript</caption> </table>



<div id="results"></div>


推荐阅读