jQuery order by date in data attribute

前端 未结 3 2000

If i have this markup:

item 1

item 1

3条回答
  •  遥遥无期
    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);
    })
    

提交回复
热议问题