简体   繁体   English

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

[英]date time and alphabet wise sort in html table using javascript

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 嗨,我是网页开发人员的新手,我需要在点击表格标题时按日期和字母顺序对表格进行排序

在此输入图像描述

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 ....... 请对此提出一些想法或建议.......

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 sort function . 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>   

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. 你会在他们的网站上找到演示。

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 Demo for sorting the date and time 现场演示用于对日期和时间进行排序

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 Obejct

call them as [jsonObject].sort(sortDesc) or [jsonObject].sort(sortAsc) 将它们称为[jsonObject].sort(sortDesc) or [jsonObject].sort(sortAsc)

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,...). 您可以以递增的方式为日期列提供id,即第1行col1将为date_1,然后row2和col1将为date_2,将其应用于两个列(notify_1,notify_2,...)。 Have a hidden field on form that consists the no of rows. 在包含no行的表单上有一个隐藏字段。 on the basis of it you may apply a loop up to it then can use any sorting algo on td's inner html. 在它的基础上你可以应用一个循环,然后可以使用任何排序算法在td的内部HTML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM