How to sort a random div order in jQuery?

后端 未结 4 1066
轻奢々
轻奢々 2021-01-07 14:20

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

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


        
4条回答
  •  天涯浪人
    2021-01-07 15:04

    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);
    }
    

提交回复
热议问题