How to sort a random div order in jQuery?

2019-02-16 03:02发布

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/

4条回答
Summer. ? 凉城
2楼-- · 2019-02-16 03:15

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);
}
查看更多
我命由我不由天
3楼-- · 2019-02-16 03:20

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

查看更多
Summer. ? 凉城
4楼-- · 2019-02-16 03:32

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);
}
查看更多
闹够了就滚
5楼-- · 2019-02-16 03:33

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>');
}
查看更多
登录 后发表回答