javascript 单击表格标题时对表格中的行进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12190171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:32:44  来源:igfitidea点击:

Sorting rows in the table as we click on the table header

javascriptjqueryhtmlcss

提问by teenu

I have a task of sorting the table row in a table. The data in the table is a mixture of everything like date, number, string etc etc.

我的任务是对表格中的表格行进行排序。表中的数据是日期、数字、字符串等所有内容的混合。

I have gone through many links where I found some are directed to the ready library. Which is of no use to me. Finally going through lot of things I have made my own using all tits and bits. which is working only for number

我浏览了许多链接,我发现其中一些链接指向了现成的库。这对我没有用。终于经历了很多事情,我用所有的乳房和小东西做了我自己的事情。这仅适用于数字

This is the script:

这是脚本:

  $(document).ready(function () {

        //grab all header rows
        $('th').each(function (column) {
            $(this).addClass('sortable').click(function () {
                    var findSortKey = function ($cell) {
                        return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase();

                    };
                    var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
                    var $rows = $(this).parent().parent().parent().find('tbody tr').get();

                    //loop through all the rows and find
                    $.each($rows, function (index, row) {
                        row.sortKey = findSortKey($(row).children('td').eq(column));
                    });

                    //compare and sort the rows alphabetically or numerically
                    $rows.sort(function (a, b) {
                        if (a.sortKey.indexOf('-') == -1) {
                            if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
                                return -sortDirection;
                            }
                            if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
                                return sortDirection;
                            }
                        } else {
                            if (a.sortKey < b.sortKey) {
                                return -sortDirection;
                            }
                            if (a.sortKey > b.sortKey) {
                                return sortDirection;
                            }
                        }
                        return 0;
                    });

                    //add the rows in the correct order to the bottom of the table
                    $.each($rows, function (index, row) {
                        $('tbody').append(row);
                        row.sortKey = null;
                    });

                    //identify the column sort order
                    $('th').removeClass('sorted-asc sorted-desc');
                    var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
                    sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');

                    //identify the column to be sorted by
                    $('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
                });
            });
        });

This is the style for the document:

这是文档的样式:

    <style>
    root
    {
        display: block;
    }

    th.sortable
    {
        color: #666;
        cursor: pointer;
        text-decoration: underline;
    }

        th.sortable:hover
        {
            color: black;
        }

    th.sorted-asc, th.sorted-desc
    {
        color: black;
        background-color: cadetblue;
    }
</style>

So below is the HTML part.

所以下面是HTML部分。

<table>
    <tbody>
        <tr>
            <th class="sortable">Name</th>
            <th class="sortable">Salary</th>
            <th>Extension</th>
            <th>Start date</th>
            <th>Start date (American)</th>
        </tr>
        <tr>
            <td>Bloggs, Fred</td>
            <td>000.00</td>
            <td>1353</td>
            <td>18/08/2003</td>
            <td>08/18/2003</td>
        </tr>
        <tr>
            <td>Turvey, Kevin</td>
            <td>1200.00</td>
            <td>2342</td>
            <td>02/05/1979</td>
            <td>05/02/1979</td>
        </tr>
        <tr>
            <td>Mbogo, Arnold</td>
            <td>010.12</td>
            <td>2755</td>
            <td>09/08/1998</td>
            <td>08/09/1998</td>
        </tr>
        <tr>
            <td>Shakespeare, Bill</td>
            <td>2000.00</td>
            <td>3211</td>
            <td>12/11/1961</td>
            <td>11/12/1961</td>
        </tr>
        <tr>
            <td>Shakespeare, Hamnet</td>
            <td>00</td>
            <td>9005</td>
            <td>01/01/2002</td>
            <td>01/01/2002</td>
        </tr>
        <tr>
            <td>Fitz, Marvin</td>
            <td>00</td>
            <td>5554</td>
            <td>22/05/1995</td>
            <td>05/22/1995</td>
        </tr>
    </tbody>
</table>

采纳答案by Jon P

Sounds like homework, which is fine, as you have shown some effort yourself. If you are not allowed to tablesorter, download it, I think there is a debug version, and have a look at the code. That should help you in your quest.

听起来像家庭作业,这很好,因为你自己已经表现出一些努力。如果你不允许tablesorter,下载它,我认为有一个调试版本,看看代码。这应该对你的追求有所帮助。

If this is homework, remember out in the real world that a golden rule of programming is don't re-invent the wheel. If there is a plug in that meets your needs, use it.

如果这是家庭作业,请记住在现实世界中编程的黄金法则是不要重新发明轮子。如果有满足您需求的插件,请使用它。

Fixing What you have

修复你所拥有的

The problem with your code as it stands is:

您的代码目前存在的问题是:

if (a.sortKey.indexOf('-') == -1) {
    if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
        return -sortDirection;
     }

     if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
          return sortDirection;
     }
} else {
    //Non numeric sort
}

Here you are always trying to sort as an integer if adoes not contain -. A very rough fix is:

在这里,如果a不包含-. 一个非常粗略的修复是:

if (a.sortKey.indexOf('-') == -1 && (!isNaN(a.sortKey) && !isNaN(a.sortKey))) {
//Rough Numeracy check                          

    if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
        return -sortDirection;
    }

    if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
        return sortDirection;
    }

 } else {
    //Non numeric sort
 }

Here is a working fidle.

这是一个工作小提琴

Keep in mind this is a very rough numeracy check you will probably need other checks and balances for other data types.

请记住,这是一个非常粗略的算术检查,您可能需要对其他数据类型进行其他检查和平衡。