jQuery order by date in data attribute

前端 未结 3 1998

If i have this markup:

item 1

item 1

相关标签:
3条回答
  • 2020-12-24 09:58

    The custom function suggested in Joseph's answer (the currently accepted solution) should return a numeric value, not a boolean. See This other question where this issue has already been raised showing that this function will not work in IE.

    The "dates.compare(a,b)" function defined here looks like a better fit for use in jQuery's sort method.

    0 讨论(0)
  • 2020-12-24 10:06

    Demo

    Super simple with an array sort:

    $("p").sort(function(a,b){
        return new Date($(a).attr("data-date")) > new Date($(b).attr("data-date"));
    }).each(function(){
        $("body").prepend(this);
    })
    

    Reverse order (in case I misunderstood you) is as easy as flipping the greater than symbol

    $("p").sort(function(a,b){
        return new Date($(a).attr("data-date")) < new Date($(b).attr("data-date"));
    }).each(function(){
        $("body").prepend(this);
    })
    
    0 讨论(0)
  • 2020-12-24 10:10
    function sortDates(a, b)
    {
        return new Date(b).getTime() - new Date(a).getTime();
    }
    
    var dates = [];
    var _old;
    
    $('p').each(function(){
        _old = $(this).parent();
        dates.push($(this).data('date'));
    });
    
    var sorted = dates.sort(sortDates);
    var _new = $('<div/>').insertBefore(_old);
    
    $.each(sorted,function(i,val){
        $('p[data-date="' + val + '"]').appendTo(_new);
    });
    
    _old.remove();
    

    Working demo: http://jsfiddle.net/AlienWebguy/JhgSw/

    0 讨论(0)
提交回复
热议问题