Looking for a javascript solution to reorder divs

2020-04-14 09:08发布

I have some divs in the page that show different things of the same kind, for example offers, now offers have ending time, and also posted time, if the user wants to order by ending time, or posted time, they should be re ordered.

I'm looking for a javascript solution that could do that, any particular libraries under Ext JS , or JQuery would work

Here is how these divs look like

<div data-sortunit="1" data-sort1="40" data-sort2="156" data-sort3="1"
data-sort4="1317620220" class="item">
</div>

<div data-sortunit="2" data-sort1="30" data-sort2="116" data-sort3="5"
data-sort4="1317620220" class="item">
</div>

<div data-sortunit="3" data-sort1="10" data-sort2="157" data-sort3="2"
data-sort4="1317620220" class="item">
</div>

So I wanna be able to sort these divs based on data-sortN, N being an integer

2条回答
做自己的国王
2楼-- · 2020-04-14 09:29

Edit: OK, now that you've supplied some HTML, here's javascript code that will sort that specific HTML by the desired column number:

function sortByDataItem(containerID, dataNum) {
    var values = [];
    $("#" + containerID + " .item").each(function(index) {
        var item = {};
        item.index = index;
        item.obj = this;
        item.value = $(this).data("sort" + dataNum);
        values.push(item);
    });
    values.sort(function(a, b) {return(b.value - a.value);});
    var container = $("#" + containerID);
    for (var i = 0; i < values.length; i++) {
        var self = $(values[i].obj);
        self.detach();
        container.prepend(self);
    }
    return;
}


$("#sort").click(function() {
    var sortValue = $("#sortColumn").val();
    if (sortValue) {
        sortValue = parseInt(sortValue, 10);
        if (sortValue && sortValue > 0 && sortValue <= 3) {
            sortByDataItem("container", sortValue);
            return;
        }
    }
    $("#msg").show(1).delay(5000).fadeOut('slow');
});

You can see it work here in a jsFiddle: http://jsfiddle.net/jfriend00/JG32X/


Since you've given us no HTML to go on, I've made my own HTML and shown you how you can use jQuery to sort:

HTML:

<button id="sort">Sort</button><br>
<div id="productList">
    <div class="row"><div class="productName">Popcorn</div><div class="price">$5.00</div></div>
    <div class="row"><div class="productName">Peanuts</div><div class="price">$4.00</div></div>
    <div class="row"><div class="productName">Cookie</div><div class="price">$3.00</div></div>
    <div class="row"><div class="productName">Beer</div><div class="price">$5.50</div></div>
    <div class="row"><div class="productName">Soda</div><div class="price">$4.50</div></div>
</div>

Javascript (run after page is loaded):

$("#sort").click(function() {
    var prices = [];
    // find all prices
    $("#productList .price").each(function(index) {
        var str = $(this).text();
        var item = {};
        var matches = str.match(/\d+\.\d+/);
        if (matches && matches.length > 0) {
            // parse price and add it to the prices array
            item.price = parseFloat(matches[0]);
            item.row = $(this).closest(".row").get(0);
            item.index = index;
            prices.push(item);
        }
    });
    // now the prices array has all the prices in it
    // sort it using a custom sort function
    prices.sort(function(a, b) {
        return(a.price - b.price);
    });
    // now pull each row out and put it at the beginning
    // starting from the end of the prices list
    var productList = $("#productList");
    for (var i = prices.length - 1; i >= 0; i--) {
        var self = $(prices[i].row);
        self.detach();
        productList.prepend(self);        
    }
});

And, a jsFiddle that shows it in action: http://jsfiddle.net/jfriend00/vRdrA/.

查看更多
乱世女痞
3楼-- · 2020-04-14 09:38

I made a tiny jqueryPlugin out of jfriend00's answer:

(function($){
   $.fn.sortChildrenByDataKey = function(key, desc){
      var i, els = this.children().sort(function(a, b) {return (desc?1:-1)*($(a).data(key) - $(b).data(key));});
      for (i = 0; i < els.length; i++) {
          this.prepend($(els[i]).detach());
      }
      return this;
  };
})(jQuery);

Your HTML:

<div id="myContainer">
  <div data-myKey="4"> ... </div>
  <div data-myKey="2"> ... </div>
  ...
</div>

Usage:

$('div#myContainer').sortChildrenByDataKey('myKey', true_or_false);

The children of the container can be any Elements. Its only important, that they are immediate children and have data-X key.

Thank you, jfriend00!!

查看更多
登录 后发表回答