通过jQuery对随机字段项进行排序

时间:2012-12-21 13:46:06

标签: javascript jquery sorting random

我有一个HTML幻灯片菜单。有以下内容:

<div class="slide">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/1.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/2.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/3.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/4.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/5.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/6.png" alt="">
</div>

我想要,每次刷新都会随机排序。我用了这段代码:

function reorder() {
    var grp = $(".slide").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();
    $(".slide").append($(grp));
}

function orderPosts() {
    $(".slide").html(orig);
}​

但是不要工作。我可能做错了什么?

4 个答案:

答案 0 :(得分:2)

有一种更简单的方法可以做到这一点。由于jQuery集合类似于Array,因此可以在它们上调用本机Array原型。因此,使用原生Array.sort,您的代码将被重写为:

var grp = $(".slide").children(); // the original collection, if you want to save it...

Array.prototype.sort.call(grp, function() {
    return Math.round(Math.random())-0.5;
});

$('.slide').empty().append(grp);

以下是演示:http://jsfiddle.net/JTGfC/

答案 1 :(得分:1)

我不确定这是否是100%犹太教,但你可以在这里应用Fisher-Yates,而不依赖于jQuery。

fisherYates(document.getElementsByClassName('slide')[0]);

// Fisher-Yates, modified to shuffle DOM container's children instead of an array.
function fisherYates (node)
{
  var children = node.children,
  n = children.length;

  if (!n) {
    return false;
  }

  while (--n) {
     var i = Math.floor( Math.random() * ( n + 1 ) ),
     c1 = children[n];

     node.insertBefore(c1, children[i]);
   }
}

Demo

答案 2 :(得分:0)

您的reorder()功能很好,我在这个小提琴中进行了测试:http://jsfiddle.net/kokoklems/YpjwE/

虽然我没有使用第二个函数orderPosts()

答案 3 :(得分:0)

这应该适合你:

function reorder() {
    var grp = $(".slide").children();
    var cnt = grp.length;

    var indexes = [];
    // Build a array from 0 to cnt-1 
    for (var i = 0; i < cnt; i++) {
        indexes.push(i);
    } 
    // Shuffle this array. This random array of indexes will determine in what order we add the images.
    indexes = shuffle(indexes);

    // Add the images. (No need to remove them first, .append just moves them)
    for (var i = 0; i < cnt; i++) {
        $(".slide").append($(grp[indexes[i]]));
    }
}

function shuffle(o){
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

Shuffle function source

Working sample (我使用跨度代替图片,以更好地显示结果)

相关问题