How to sort a random div order in jQuery?

后端 未结 4 1064
轻奢々
轻奢々 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 14:51

    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);
    }
    
    0 讨论(0)
  • 2021-01-07 14:59

    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>');
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-07 15:04

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

    0 讨论(0)
提交回复
热议问题