javascript 使用javascript在html表中按日期时间和字母顺序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15609012/
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-27 01:24:14  来源:igfitidea点击:

date time and alphabet wise sort in html table using javascript

javascriptjqueryhtml

提问by Kumar

hi i am new to web page developer, i need to sort my table in date wise and alphabet wise on click of table header

嗨,我是网页开发人员的新手,我需要在单击表格标题时按日期和字母顺序对表格进行排序

enter image description here

在此处输入图片说明

this is my table.... the data's inside the table are generated dynamically using ajax....

这是我的表......表内的数据是使用ajax动态生成的......

my need is

我的需要是

  • on click of date header it should sort according to date
  • on click of notify header it should sort according to alphabet
  • 点击日期标题,它应该根据日期排序
  • 点击通知标题,它应该根据字母排序

please give some ideas or suggestions about this .......

请对此提出一些想法或建议......

回答by rab

I made example using jQuery library, and added it in http://jsfiddle.net/bURg4/2/

我使用 jQuery 库制作了示例,并将其添加到http://jsfiddle.net/bURg4/2/

jQuery selector returns is array object, which has native array sortfunction .

jQuery 选择器返回的是数组对象,它具有原生的数组sort功能。

$('table tbody tr').sort( function( a , b ) {

     // do compare here
});

Hope this will helps ..

希望这会有所帮助..

copy and paste following code into a file .. rename it into test.html

将以下代码复制并粘贴到文件中..将其重命名为 test.html

<html>
    <head>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    </head>
    <body>
        <table border="1">
            <thead>
                <tr>
                    <th data-key="id" data-column="0" data-order="asc">id</th>
                    <th data-key="date" data-column="1" data-order="asc">date</th>
                    <th data-key="notify" data-column="2" data-order="asc">notify</th>

                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>31-03-2013 06:12:57 PM</td>
                    <td>gold</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>31-03-2013 06:14:57 PM</td>
                    <td>diamond</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>31-03-2013 06:10:57 PM</td>
                    <td>silver</td>
                </tr>
            </tbody>
        </table>    
        <script type="text/javascript">

            function getDate( str ) {

                var ar =  /(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2}) ([AM|PM]+)/ 
                     .exec( str ) 

                return new Date(
                    (+ar[3]),
                    (+ar[2])-1, // Careful, month starts at 0!
                    (+ar[1]),
                    (+ar[4])+ ( ar[7]=='PM'? 12 :0 ),
                    (+ar[5]),
                    (+ar[6])
                );
            };

            $( function(){


                var sorter = {

                    order   : [1,-1],
                    column  : 0 ,
                    key     :'id' ,

                    setOrder : function( k ){

                        this.order  = ({ 
                            asc :[1,-1], desc:[-1,1] 
                        })[k] || this.order ;

                        return this;
                    },
                    setColumn : function( c ){

                        this.column  = c || this.column ;
                        return this;
                    },

                    setKey : function( k ) {
                        this.key  = k || this.key;
                        return this;
                    },

                    sort : function( els ) {

                        var sortFunc = this.key;

                        return els.sort( this[ sortFunc ]);        
                    },

                    getValue : function( a, b ){

                        return {
                            a : $(a).find('td:eq('+ sorter.column +')').text(),
                            b : $(b).find('td:eq('+ sorter.column+')').text()
                        }
                    },
                    comp : function( val ) {

                            if ( val.a == val.b ) {
                                return 0;
                            }

                            return  val.a > val.b ? 
                                    sorter.order[0]:sorter.order[1] ; 

                    },
                    id : function( a , b ){

                            var val = sorter.getValue(a,b);

                            val.a = parseInt( val.a , 10 );
                            val.b = parseInt( val.b , 10 );

                            return sorter.comp( val );        

                    },

                    notify : function( a , b ){

                            var val = sorter.getValue(a,b);
                            return sorter.comp( val );           

                    },
                    date : function( a , b ){

                            var val = sorter.getValue(a,b);

                            val.a = getDate( val.a );
                            val.b = getDate( val.b );

                            return sorter.comp( val ); 

                    }
                }

                $('table thead').on('click', 'th', function(){

                        var sorted = sorter.setOrder( $(this).attr('data-order') )
                                           .setColumn( $(this).attr('data-column') )
                                           .setKey( $(this).attr('data-key') )
                                           .sort(  $('table tbody tr') );


                        $('table tbody').empty().append( sorted );  

                        $('table thead th').not( this )
                                           .attr('data-order' ,'asc');

                        $(this).attr(
                            'data-order',  
                            ( $(this).attr('data-order') == 'asc' ? 'desc' :'asc') 
                        );

                });
            });
        </script>

    </body>
</html>   

回答by Magnus Karlsson

I would use a small jquery plugin.

我会使用一个小的 jquery 插件。

I have tried http://www.datatables.net/but think its too large for my need thats a little bigger than yours so I would suggest http://tablesorter.com/docs/which fits you speification perfect.

我已经尝试过http://www.datatables.net/,但认为它对于我的需求来说太大了,比你的要大一点,所以我建议http://tablesorter.com/docs/适合你的规格完美。

You'll find demos on their sites.

你会在他们的网站上找到演示。

回答by Prasath K

Store the corresponding values in an array and do sorting

将相应的值存储在一个数组中并进行排序

To sort array by date, Use this

要按日期对数组进行排序,请使用此

array.sort(function(a,b){
var c = new Date(a.date);
var d = new Date(b.date);
return c-d;
});

To sort array by alphabet , use basic sort()function

要按字母表对数组进行排序,请使用基本的sort()函数

Live Demofor sorting the date and time

用于排序日期和时间的Live Demo

回答by A.T.

function sortAsc(a, b) {
    var aSort = a.Text.toLowerCase(), //Text is the field on which we make sort
        bSort = b.Text.toLowerCase();
    if (aSort === bSort) return 0;
    return aSort < bSort ? 1 : -1;
}
function sortDesc(a, b) {
    var aSort = a.Text.toLowerCase(), //Text is the field on which we make sort
        bSort = b.Text.toLowerCase();
    if (aSort === bSort) return 0;
    return aSort > bSort ? 1 : -1;
}

i use these two methods for sorting Json Obejct

我使用这两种方法对 Json 对象进行排序

call them as [jsonObject].sort(sortDesc) or [jsonObject].sort(sortAsc)

称他们为 [jsonObject].sort(sortDesc) or [jsonObject].sort(sortAsc)

回答by Prateek Shukla

You may give id for date column in increasing manner that is Row 1 col1 will be date_1 then row2 and col1 will be date_2 like that, apply it to both columns (notify_1,notify_2,...). Have a hidden field on form that consists the no of rows. on the basis of it you may apply a loop up to it then can use any sorting algo on td's inner html.

您可以以递增的方式为日期列指定 id,即第 1 行 col1 将是 date_1 然后 row2 和 col1 将是 date_2 那样,将其应用于两列(notify_1、notify_2、...)。在表单上有一个包含行数的隐藏字段。在此基础上,您可以对其应用循环,然后可以在 td 的内部 html 上使用任何排序算法。