最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort divs by datetime with JS - Stack Overflow

programmeradmin2浏览0评论

I have a script which creates a lot of divs with the a data-date attribute and has a time format of Tue Aug 16 2016 12:27:21 GMT+0100 (BST)

An example set could be:

<div class="socialBox" data-date="Tue Aug 10 2016 12:30:21 GMT+0100 (BST)" data-type="twitter">
<div class="socialBox" data-date="Tue Aug 14 2016 12:10:21 GMT+0100 (BST)" data-type="facebook">
<div class="socialBox" data-date="Tue Aug 13 2016 15:27:21 GMT+0100 (BST)" data-type="youtube">
<div class="socialBox" data-date="Tue Aug 03 2016 18:27:21 GMT+0100 (BST)" data-type="instagram">

The divs are appended to a blank div from a variety of different functions and then I run the JS to sort the divs and append it to the original blank div again but I can't seem to get it to work.

Here is the script

loadTwitter(twitter);
loadFacebook(facebook);
loadYoutube(youtube);
loadInstagram(instagram);

// DOESN'T WORK YET (THE BELOW)

var board = $("#social-board");
var boards = board.children('.socialBox');

boards.sort(function(a, b) {
    var an = $(a).data("date").getTime();
    var bn = $(b).data("date").getTime();

    if(an > bn) {
        return 1;
    }

    if(an < bn) {
        return -1;
    }

    return 0;
});

boards.detach().appendTo(board);

Could anyone help me out? I'm not sure if its the appending to the div element or the JS sort function itself.

I have a script which creates a lot of divs with the a data-date attribute and has a time format of Tue Aug 16 2016 12:27:21 GMT+0100 (BST)

An example set could be:

<div class="socialBox" data-date="Tue Aug 10 2016 12:30:21 GMT+0100 (BST)" data-type="twitter">
<div class="socialBox" data-date="Tue Aug 14 2016 12:10:21 GMT+0100 (BST)" data-type="facebook">
<div class="socialBox" data-date="Tue Aug 13 2016 15:27:21 GMT+0100 (BST)" data-type="youtube">
<div class="socialBox" data-date="Tue Aug 03 2016 18:27:21 GMT+0100 (BST)" data-type="instagram">

The divs are appended to a blank div from a variety of different functions and then I run the JS to sort the divs and append it to the original blank div again but I can't seem to get it to work.

Here is the script

loadTwitter(twitter);
loadFacebook(facebook);
loadYoutube(youtube);
loadInstagram(instagram);

// DOESN'T WORK YET (THE BELOW)

var board = $("#social-board");
var boards = board.children('.socialBox');

boards.sort(function(a, b) {
    var an = $(a).data("date").getTime();
    var bn = $(b).data("date").getTime();

    if(an > bn) {
        return 1;
    }

    if(an < bn) {
        return -1;
    }

    return 0;
});

boards.detach().appendTo(board);

Could anyone help me out? I'm not sure if its the appending to the div element or the JS sort function itself.

Share Improve this question asked Aug 16, 2016 at 16:04 WebDevDannoWebDevDanno 1,1222 gold badges22 silver badges50 bronze badges 1
  • 2 Note: All those parisons can be turned into return $(a).data("date") - $(b).data("date"); if .data("date") returns a Date instance (as it seems to), because A) The - operator will coerce the dates to numbers, which is equivalent to calling getTime, and B) You don't have to specifically return -1, 1, and 0; any negative or positive number is fine for the first two. – T.J. Crowder Commented Aug 16, 2016 at 16:06
Add a ment  | 

3 Answers 3

Reset to default 9

You can do this by:

  1. Detaching them up front and then using .get to get a real array instead of a jQuery object.

  2. Sorting them (which can be a lot simpler)

  3. Appending that array back to #social-board

so:

var boards = board.children('.socialBox').detach().get();
// --------------------------------------^^^^^^^^^^^^^^^

// A bit shorter :-)
boards.sort(function(a, b) {
  return new Date($(a).data("date")) - new Date($(b).data("date"));
});

board.append(boards); // <== switched this to append

Live example:

// Wait a sec so we can see the old order...
setTimeout(function() {
  // Now sort them

  var board = $("#social-board");
  var boards = board.children('.socialBox').detach().get();

  boards.sort(function(a, b) {
    return new Date($(a).data("date")) - new Date($(b).data("date"));
  });

  board.append(boards);
}, 600);
<div id="social-board">
  <div class="socialBox" data-date="2016-08-10T11:30:21.000Z" data-type="twitter">2016-08-10T11:30:21.000Z</div>
  <div class="socialBox" data-date="2016-08-03T17:27:21.000Z" data-type="instagram">2016-08-03T17:27:21.000Z</div>
  <div class="socialBox" data-date="2016-08-14T11:10:21.000Z" data-type="facebook">2016-08-14T11:10:21.000Z</div>
  <div class="socialBox" data-date="2016-08-13T14:27:21.000Z" data-type="youtube">2016-08-13T14:27:21.000Z</div>
</div>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Note: You cannot rely on the JavaScript Date object parsing dates in the string format you've used. Note the ISO format I've used in the snippet instead.


Side note: Unless you're using the features of data, you may want to use attr instead. data is not just an accessor for data-* attributes. It's both more and less than that.

Your idea is right, but your logic is slightly off in your sort function. This is the code I use to sort dates:

var reverse = false; // ascending/descending flag
var board = $("#social-board");
var boards = board.children('.socialBox');
var orderedBoards = boards.slice().sort(function (elem1, elem2) {
  var value1 = new Date($(elem1).data("date")).getTime(),
      value2 = new Date($(elem2).data("date")).getTime();
  if (reverse) {
    // descending
    return -(value1 > value2) || +(value1 < value2) || (isNaN(value1)) - (isNaN(value2));
  }
  // ascending
  return +(value1 > value2) || -(value1 < value2) || (isNaN(value1)) - (isNaN(value2));
});
board.empty().append(orderedBoards);

I have a solution:

HTML:

<ul class="sort-list">
    <li class="sort-item" data-event-date="2018-06-30 22:00">3</li>
    <li class="sort-item" data-event-date="2018-06-29 21:00">2</li>
    <li class="sort-item" data-event-date="2018-06-27 22:00">1</li>
    <li class="sort-item" data-event-date="2018-07-01 22:00">4</li>
    <li class="sort-item" data-event-date="2018-07-02 22:00">5</li>

</ul>

<button onclick="chat_order()">
test
</button>

JS:

function chat_order() {
    var container = $(".sort-list");
    var items = $(".sort-item");

    items.each(function() {
       // Convert the string in 'data-event-date' attribute to a more
       // standardized date format
       var BCDate = $(this).attr("data-event-date");
       /*console.log(BCDate);
       var standardDate = BCDate[1]+" "+BCDate[0]+" "+BCDate[2];*/
       var standartDate = new Date(BCDate).getTime();
       $(this).attr("data-event-date", standartDate);
                console.log(standartDate);
    });


    items.sort(function(a,b){
        a = parseFloat($(a).attr("data-event-date"));
        b = parseFloat($(b).attr("data-event-date"));
        return a>b ? -1 : a<b ? 1 : 0;
    }).each(function(){
        container.prepend(this);
    });

}

JSFIDDLE: http://jsfiddle/2fr0vmhu/294/

发布评论

评论列表(0)

  1. 暂无评论