I have this jQuery and HTML http://jsfiddle.net/UgX3u/30/
-
Try this:
http://jsfiddle.net/UgX3u/33/
$("div.container div").sort(function(){
return Math.random()*10 > 5 ? 1 : -1;
}).each(function(){
var $t = $(this),
color = $t.attr("class");
$t.css({backgroundColor: color}).appendTo( $t.parent() );
});
.sort
is applied to jQuery like this:
$.fn.sort = [].sort
Since it doesn't perform like other jQuery methods, it isn't documented. That does mean it is subject to change, however I doubt it will ever change. To avoid using the undocumented method, you could do it like this:
http://jsfiddle.net/UgX3u/37/
var collection = $("div.container div").get();
collection.sort(function() {
return Math.random()*10 > 5 ? 1 : -1;
});
$.each(collection,function(i,el) {
var color = this.className,
$el = $(el);
$el.css({backgroundColor: color}).appendTo( $el.parent() );
});
讨论(0)
-
This example assumes you have to work with elements already on a page with classes assigned to them:
var classes = [];
// Populate classes array
// e.g., ["yellow", "red", "green", "blue", "pink", "orange", "black", "white"]
$('div.container').children().each(function (i, v) {
classes.push(v.className);
});
// Assign random color to each div
$('div.container').children().each(function (i, v) {
var color = Math.floor(Math.random()*classes.length)
$(v).css({backgroundColor: classes.splice(color,1)});
});
http://jsfiddle.net/UgX3u/40/
讨论(0)
-
var $container = $("div.container");
$container.html(shuffle($container.children().get()));
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 found here
Updated:
jsFiddle
讨论(0)