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

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

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

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

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

你的reorder()函数很好,我在这个小提琴中测试它: http : //jsfiddle.net/kokoklems/YpjwE/

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

有一种更简单的方法可以做到这一点。 由于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/

我不确定这是否是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]); } } 

演示

这应该为你做:

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

随机function源

工作样本 (我使用跨度代替图像,以更好地显示结果)