How to sort a random div order in jQuery?

2019-02-16 02:35发布

问题:

On page load, I am randomizing the order of the children divs with this Code:

function reorder() {
   var grp = $("#team-posts").children();
   var cnt = grp.length;

   var temp, x;
   for (var i = 0; i < cnt; i++) {
       temp = grp[i];
       x = Math.floor(Math.random() * cnt);
       grp[i] = grp[x];
       grp[x] = temp;
   }
   $(grp).remove();
   $("#team-posts").append($(grp));
}

I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/

回答1:

Keep original copy like following before calling reorder() function and use that for reorder later.

var orig = $("#team-posts").children();

$("#undo").click(function() {
    orderPosts();
});

function orderPosts() {
   $("#team-posts").html( orig )  ;
}

Working demo

Full Code

var orig = $("#team-posts").children(); ///caching original

reorder();

$("#undo").click(function(e) {
    e.preventDefault();
    orderPosts();
});

function reorder() {
    var grp = $("#team-posts").children();
    var cnt = grp.length;

    var temp, x;
    for (var i = 0; i < cnt; i++) {
        temp = grp[i];
        x = Math.floor(Math.random() * cnt);
        grp[i] = grp[x];
        grp[x] = temp;
    }
    $(grp).remove();
    $("#team-posts").append($(grp));
}

function orderPosts() {
    // set original order
    $("#team-posts").html(orig);
}


回答2:

How about an "undo" plugin, assuming it applies?



回答3:

Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable

$("#team-posts div").each(function() {
    var parseIntedClassname = parseInt($(this).attr("class");
    arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});

You can reorder them from there by saving their html to an array in order

$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
    $("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}


回答4:

The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:

http://www.w3schools.com/jsref/jsref_sort.asp

function orderPosts() {
    var $grp = $("#team-posts"),
        ordered = $grp.children().toArray().sort(function(a, b) {
            return parseInt($(a).text()) > parseInt($(b).text());
        });
    $grp.empty().append(ordered);
}