简体   繁体   English

在ajax中按日期对表进行排序

[英]Sort table column by date in ajax

I have a table that's displayed on button click using ajax. 我有一个表,使用ajax点击按钮时显示。 Here's a code snippet: 这是一段代码片段:

myBtn.on("click", function() {
    displayTable();
});

function displayTable(){
    $.ajax({
        url:'url to a function in controller',
        type: "GET",
        //data: {val : val},
        dataType: 'json',
        success: function(data){  

            // some codes here

            $.each(data.documents, function(key, value){                        
                $("#myTable")
                .append(
                    "<tr class='" + rowClass + "'><td class='text-center'>" +                       
                        value.title +
                    "</td><td class='text-center'>" +               
                        value.time1.replace(/-/g, "/") +
                    "</td><td class='text-center'>" +                  
                        value.time2.replace(/-/g, "/") +
                    "</td></tr>"
                );
            });
        }
    });
}

After this, a table is displayed but it is not sorted by date ( value.time2 ). 在此之后,将显示一个表,但不按日期排序( value.time2 )。 I tried this but not working: 我尝试了这个但没有工作:

$("#myTable thead tr").find('th').eq(3).sort(function(a,b){
    return new Date($(a).value.time2) > new Date($(b).value.time2);
});

Do you have any idea how to do this? 你知道怎么做吗? How do I sort it by date ( value.time2 )? 我如何按日期排序( value.time2 )?

The best way would be to request the server to sort the values for you. 最好的方法是请求服务器为您排序值。 However, if you need to perform this on client side, you can simply sort data.documents before adding it to the page. 但是,如果需要在客户端执行此操作,则可以在将data.documents添加到页面之前对其进行简单排序。 For example: 例如:

        data.documents = data.documents.map(function(item) {
            // Fix display
            item.time1 = item.time1.replace(/-/g, "/");
            item.time2 = item.time2.replace(/-/g, "/");
            return item;
        });
        data.documents.sort(function(a, b) {
            // Custom sorting function
            return new Date(a.time2) > new Date(b.time2);
        });

        $.each(data.documents, function(key, value){                        
            $("#myTable")
            .append(
                "<tr class='" + rowClass + "'><td class='text-center'>" +                       
                    value.title +
                "</td><td class='text-center'>" +               
                    value.time1 +
                "</td><td class='text-center'>" +                  
                    value.time2 +
                "</td></tr>"
            );
        });

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

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