使用多种排序对多个html表进行排序

时间:2015-10-02 02:11:43

标签: javascript jquery html sorting

我的页面上有几个html表格,我希望能够根据其中一个单元格值的值对它们进行排序。这是我的表格的一个例子

<div id="tables">
    <table class="sortable">
        <tr>
            <td>Comic Book Name</td>
            <td id="comic">Batman</td>
        </tr>
        <tr>
            <td>Main Character</td >
            <td ="character">Bruce Wayne</td>
        </tr>
        <tr>
            <td>Hero Name</td>
            <td id="hero">Batman</td>
        </tr>
        <tr>
            <td>Published</td>
            <td id="publish">05/01/1940</td>
        </tr>
    </table>
    <table class="sortable">
        <tr>
            <td>Comic Book Name</td>
            <td id="comic">Green Arrow</td>
        </tr>
        <tr>
            <td>Main Character</td >
            <td ="character">Oliver Queen</td>
        </tr>
        <tr>
            <td>Hero Name</td>
            <td id="hero">Green Arrow</td>
        </tr>
        <tr>
            <td>Published</td>
            <td id="publish">11/01/1941</td>
        </tr>
    </table>
</div>

我提供以下下拉菜单以允许用户过滤。

<select id="OrderBy">
 <option selected="selected" value="comic">Comic Name</option>
 <option value="character">Character Name</option>
 <option value="hero">Hero Name</option>
 <option value="publish">Earliest Publish Date</option>
</select>

我希望这里按照漫画书名称的字母顺序对表格进行排序,选择漫画名称时,按字符名称选择字符名称等按字母顺序排序等。

这是我到目前为止提出的javascript / jquery。我确信这可以做得更好,但我是Javascript和Jquery的新手。

$('#OrderBy').on('change', function () {
    _order = $('#OrderBy').val();
    switch (_order) {
        case "comic":
            $('#sortable').sort(function () {

            });
            break;
        case "character":
            $('#sortable').children().sort(function (a, b) {
            });
            break;
        case "publish":
            $('#sortable').sort(function () {
            });
            break;
        case "publish":
            $('#sortable').sort(function () {
                if ($(b).children().find('#Hours').text() - $(a).children().find('#publish').text() <= 0) {
                    return $(a) - $(b);
                }
                return $(b) - $(a);
            });
            break;
    }
});

我到处都看到有人建议使用Sorttables或tableSorter,但我只看到它们如何适用于正在排序行的单个表。我知道在这一点上每个人都在想什么,不要这样使用表格。我的问题是已经有一堆jquery和javascript支持表格,而且我没有足够的语言来重写所有这些。

我喜欢按照With ... End With statement所述将所有内容推送到堆栈的想法,但我总是生成一个关于我的数组/堆栈未定义的错误。

2 个答案:

答案 0 :(得分:1)

首先,你不应该多次使用相同的id,而是使用类:

<div id="tables">

    <table class="sortable">
        <tr>
            <td>Comic Book Name</td>
            <td class="comic">Green Arrow</td>
        </tr>
        <tr>
            <td>Main Character</td >
            <td class="character">Oliver Queen</td>
        </tr>
        <tr>
            <td>Hero Name</td>
            <td class="hero">Green Arrow</td>
        </tr>
        <tr>
            <td>Published</td>
            <td class="publish">11/01/1941</td>
        </tr>
    </table>
    <table class="sortable">
        <tr>
            <td>Comic Book Name</td>
            <td class="comic">Batman</td>
        </tr>
        <tr>
            <td>Main Character</td >
            <td class="character">Bruce Wayne</td>
        </tr>
        <tr>
            <td>Hero Name</td>
            <td class="hero">Batman</td>
        </tr>
        <tr>
            <td>Published</td>
            <td class="publish">05/01/1940</td>
        </tr>
    </table>
</div>

对于您的问题,我会使用原生的Array.prototype.sort方法

var tables = [];
var $tables = $("table.sortable");
var container = $("#tables");
// this is the only specific case, as the date does not start by the year
// it will be used to sort by publish date
function sortByDate(a, b) {
    return new Date(a.publish).getTime() - new Date(b.publish).getTime();
}

function sortTables(order) {
    var sort;
    if (order === "publish") {
        tables = tables.sort(sortByDate);
    } else {
        tables = tables.sort(function(a, b) {
            return a[order] < b[order] ? -1 : 1;
        });
    }
    tables.forEach(function(data,i) {
        tables[i].$el.detach()
        container.append(tables[i].el);
    });
}

function init() {
    //populate the tables array that will be sorted
    $tables.each(function(i, val) {
        var $this = $(this);
        tables.push({
            $el: $this,
            el: this,
            comic: $this.find(".comic").text(),
            character: $this.find(".character").text(),
            hero: $this.find(".hero").text(),
            publish: $this.find(".publish").text()
        });
    });
    $("#OrderBy").on("change", function(event) {
        sortTables(event.currentTarget.value);
    });
    //by default sort by Hero
    sortTables("hero");
}
init();

答案 1 :(得分:0)

主要是,当您在两个不同的表中有数据时,排序不会发生。为了使它成为可能,你需要将id放到它们身上,而不仅仅是类,因为你的主要问题不是CSS。同样,如果您将相同的ID放在不同的内容中,则无法专门发现它。因此,调试的代码将是:

<div id="tables">
<table id="tbl1" class="sortable">
    <tr>
        <td>Comic Book Name</td>
        <td class="comic">Batman</td>
    </tr>
    <tr>
        <td>Main Character</td >
        <td class="character">Bruce Wayne</td>
    </tr>
    <tr>
        <td>Hero Name</td>
        <td class="hero">Batman</td>
    </tr>
    <tr>
        <td>Published</td>
        <td class="publish">05/01/1940</td>
    </tr>
</table>

<table id="tbl2" class="sortable">
    <tr>
        <td>Comic Book Name</td>
        <td class="comic">Green Arrow</td>
    </tr>
    <tr>
        <td>Main Character</td >
        <td class="character">Oliver Queen</td>
    </tr>
    <tr>
        <td>Hero Name</td>
        <td class="hero">Green Arrow</td>
    </tr>
    <tr>
        <td>Published</td>
        <td class="publish">11/01/1941</td>
    </tr>
</table>

您的下拉菜单(过滤器框)已正确定义。现在,在js代码中,存在一些语法错误。 比如,'class'标识符是'。','id'标识符是'#',你使用'#'而不是'。'一些地方:

switch (_order) {
    case "comic":
        $('#sortable').sort(function () {});

调试代码将是:

$('#OrderBy').on('change', function () {
_order = $('#OrderBy').val();
switch (_order) {
    case "comic":
        $('.sortable').sort(function () {});
        break;
    case "character":
        $('.sortable').children().sort(function (a, b) {
        });
        break;
    case "publish":
        $('.sortable').sort(function () {
        });
        break;
    case "publish":
        $('.sortable').sort(function () {
            if ($(b).children().find('#Hours').text() - $(a).children().find('#publish').text() <= 0) {
                return $(a) - $(b);
            }
            return $(b) - $(a);
        });
        break;
}});

没有正式的表sort()函数jquery库。它只适用于数组,但你不会在这里有任何数组。 所以我们自己做一个排序功能。我们可以将它命名为“sortTable()”。这个代码应该是:

<!--   -------------------------------------------------------------- -->
<!-- Secondary functions -->

<!-- Creates a new table to display the sorted Table -->

function createEmptyTable(){
    var outerDiv = document.createElement('div');
    outerDiv.setAttribute('id','ResultTable');
    var innerTable = doucment.createElement('table');
    innerTable.setAttribute('id','sortedTable'); 
    var newRows = new Array();
    var recordIndex = document.getElementsByClassName('comic');
    innerTable.innerHTML = "<tr> <th>Comic Book Name </th> <th>Main Character</th> <th>Hero Name</th> <th>Published</th> </tr>";
    for(var i=0; i<recordIndex.Length;i++){
        newRows[i]= document.createElement('tr');
        outerDiv.appendChild(innerTable).appendChild(newRows[i]);
        }
    }

<!--     -------------------------------------------------------------  -->

<!-- function to find out in which table chosen filter belongs -->

function recordSearch(keyWord){
    var sortableTables = document.getElementsByClassName('sortable');
    for( var i=0; i<sortableTables.length;i++){
        if($(sortableTables[i]).find(keyword)){
        return sortableTable[i];
    }
        }

<!--      -------------------------------------------------------------    -->

<!-- Primary function to sort the Table -->

function sortTable(filtered_option){

<!-- first we delete any existing sorted table -->

    if(document.getElementById('ResultTable')){
        var existingSortedTable = document.getElementbyId('ResultTable');
        existingSortedTable.removeChild(document.getElementById('sortedTable');
    }

<!-- now we create new table & put the result -->

    createEmptyTable();
    var comicNames = document.getElementsByClassName('comic');
    var characterNames = document.getElementsByClassName('character');
    var heroNames = document.getElementsByClassName('hero');
    var publishDates = document.getElementsByClassName('publish');

    switch (filtered_option) {

    case 'comic' :
        var sortedComicNames = comicNames.sort();
        for(var i=0;i<sortedComicNames.length;i++){
            var foundRecord = recordSearch(sortedComicNames[i]);
            var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
            var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
            for(var j=0;j<allFields.length;j++){
                emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
        }}
    break;

    case 'character' :
        var sortedCharacterNames= characterNames.sort();
        for(var i=0;i<characterNames.length;i++){
            var foundRecord = recordSearch(sortedCharacterNames[i]);
            var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
            var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
            for(var j=0;j<allFields.length;j++){
                emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
        }}
    break;

    case 'hero' :
        var sortedHeroNames= heroNames.sort();
        for(var i=0;i<heroNames.length;i++){
            var foundRecord = recordSearch(heroNames[i]);
            var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
            var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
            for(var j=0;j<allFields.length;j++){
                emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
        }}
    break;

    case 'publish' :
        var sortedPublishedDates= publishedDates.sort();
        for(var i=0;i<publishedDates.length;i++){
            var foundRecord = recordSearch(publishedDates[i]);
            var allFields = foundRecord.getElementByTagName('tr').getElementsByClassName('td');
            var emptyRows = document.getElementById('sortedTable').getElementsByTagName('tr');
            for(var j=0;j<allFields.length;j++){
                emptyRows[i+1].innerHTML = "<td>" + allFields[j].value + "</td>" ;
        }}
    break;  
    }
}
<!--    --------------------------------------------------------------------    -->

将它们放在一起然后尝试。如果有效,请告诉我。