I've looked around and have been able to find a piece of code that does the job but it doesn't work for all of my tags. I have a total of 8 Div tags that I want to randomize and this piece of code only allows me to randomize 7 of them. If I replace the 7 with an 8 it just shows everything开发者_运维问答 in order. I don't work with Javascript very often and have hit a road block. Any help is greatly appreciated.
<script type="text/javascript">
$(document).ready(function() {
$(".workPiece").hide();
var elements = $(".workPiece");
var elementCount = elements.size();
var elementsToShow = 7;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
elements.eq(rand).show();
++i;
}
}
});
</script>
This implementation of a Fisher-Yates shuffle seems to work quite well:
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [rev. #1]
shuffle = function(v){
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
};
// Shuffle DIVs
$(document).ready(function() {
console.log(shuffle($('div')));
});
try this
var elements = $(".workPiece");
while (elements.length) {
var rand = Math.floor(Math.random() * elements.length);
elements.eq(rand).show();
elements = elements.not(':eq(' + rand + ')');
}
But I don't know if this will work.
To make this work with all elements, you need to actually move the elements themselves around to shuffle them, instead of just randomly hiding some of them.
Here is an example jQuery plugin to do that:
(function($) {
$.fn.shuffle = function(selector, limit) {
if (limit !== undefined) {
limit -= 1;
}
return this.each(function() {
var $this = $(this);
var nodes = $this.children(selector).show().remove().get();
while (nodes.length > 0) {
var i = Math.floor(Math.random() * nodes.length);
$this.append(nodes.splice(i, 1));
}
if (limit !== undefined) {
$this.children(selector + ':gt(' + limit + ')').hide();
}
});
};
})(jQuery);
You would call it like so:
$('.grid-8').shuffle('.workPiece');
You can limit the number of visible children like so:
$('.grid-8').shuffle('.workPiece', 4);
Here's a jsFiddle for it.
精彩评论