简体   繁体   English

如何在jQuery中对随机div顺序排序?

[英]How to sort a random div order in jQuery?

On page load, I am randomizing the order of the children divs with this Code: 在页面加载时,我使用以下代码将子级div的顺序随机化:

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/ 这是我当前代码的演示http://jsfiddle.net/JsJs2/

Keep original copy like following before calling reorder() function and use that for reorder later. 在调用reorder()函数之前,请像下面那样保留原始副本,并在以后用于重新排序。

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

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 只需给每个项目一个具有相应顺序的类,然后获取每个div的类名称并将其保存到变量即可

$("#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 您可以通过将它们的html按顺序保存到数组中来从那里重新排序

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

假设适用, “撤消”插件如何?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM