根据时间戳值对li元素进行排序

时间:2017-01-19 14:28:09

标签: javascript jquery sorting

我有一个像这样的li元素列表:

<li>
   <div class="historyDateBloc">
      <span class="dateTop"></span>
      <span class="dateBottom"></span>
      <span class="hiddenDate">1481727905</span>
      <p class="historyDateText">14 Dec <br>2016</p>
   </div>
   <p class="historyMainText">Equipment shipped</p>
   <p class="historySubText">Subscription equipment shipped under cso reference 0000RPO205</p>
</li>

我想基于hiddenDate类值从UI中的列表中的最新元素到最旧元素进行排序。我怎么能用jQuery做到这一点?

2 个答案:

答案 0 :(得分:4)

使用sort()方法对集合进行排序,并在排序后使用appendTo()方法将其更新为DOM追加。

// get all li elements
$('ul li').sort(functio(a, b){
  // get difference between the content of hiddenDate element
  // where define the context as second argument inorder to get element within it
  return $('.hiddenDate', b).text() - $('.hiddenDate', a).text();
  // append back to the `ul` for updating the order
}).appendTo('ul')

答案 1 :(得分:1)

您可以这样做:

$("li").sort(function(a, b) {
  return new Date($(a).find(".hiddenDate")) > new Date($(b).find(".hiddenDate"));
}).each(function() {
  $("ul").prepend(this);
})

https://jsfiddle.net/e17wq0am/

相关问题