【问题标题】:How to sort by date before creating DOM elements如何在创建 DOM 元素之前按日期排序
【发布时间】:2015-06-27 23:00:54
【问题描述】:

我正在循环浏览一些 JSON,并希望按最新日期显示 DOM 元素。我有一个数据日期属性。在将它们创建为 DOM 元素之前,如何对数组中的每个对象进行排序?

我有以下——

$.getJSON(ytapiurl, function(data) {
  $.each(data.feed.entry, function(i, item) {
    var pubdate  = item['published']['$t'];
        htmlString +='<div class="cursor col-sm-6 col-md-3 item" data-date="' + fulldate '">Video</div>';

    console.log(new Date(pubdate).getTime());
 });
});

【问题讨论】:

  • 嗯,那么 pubdate 到底是从哪里来的?
  • pubdate 是在哪里定义的,它的格式是什么?
  • 抱歉,pubdate 是 .each 中设置的 var -- var pubdate = item['published']['$t'];

标签: javascript jquery sorting dom youtube


【解决方案1】:

假设pubdateentry数组中项的属性,则可以在创建html之前对数组进行排序

$.getJSON(ytapiurl, function (data) {
    data.feed.entry.sort(function (a, b) {
        var fd1 = new Date(a.pubdate);
        var fd2 = new Date(b.pubdate);
        return fd1.getTime() - fd2.getTime();
    })
    $.each(data.feed.entry, function (i, item) {
        var fulldate = new Date(pubdate).toLocaleDateString();
        htmlString += '<div class="cursor col-sm-6 col-md-3 item" data-date="' + fulldate '">Video</div>';
    });
});

【讨论】:

    【解决方案2】:

    技巧是使用日期对象对数组进行排序,而不是表示日期的字符串。

    var articles = [
       {pubDate: new Date(2000, 0, 1), desc:'one'},
       {pubDate: new Date(1999, 0, 1), desc:'two'},
       {pubDate: new Date(2002, 0, 1), desc:'three'},
       {pubDate: new Date(2001, 0, 1), desc:'four'}
    ];
    console.log(articles);
    articles.sort(function(a,b){
        return a.pubDate < b.pubDate; // set desc or asc here
    });
    articles.forEach(function(article){
       console.log(article.pubDate,article.desc);
       // Write to DOM here
    });
    

    返回

    Tue Jan 01 2002 00:00:00 GMT-0600 (Central Standard Time) "three"
    Mon Jan 01 2001 00:00:00 GMT-0600 (Central Standard Time) "four"
    Sat Jan 01 2000 00:00:00 GMT-0600 (Central Standard Time) "one"
    Fri Jan 01 1999 00:00:00 GMT-0600 (Central Standard Time) "two"
    

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多