jQuery,随机div顺序 [英] jQuery, random div order
问题描述
我有这个jQuery和HTML http://jsfiddle.net/UgX3u/30/
< div class =container>
< div class =yellow>< / div>
< div class =red>< / div>
< div class =green>< / div>
< div class =blue>< / div>
< div class =pink>< / div>
< div class =orange>< / div>
< div class =black>< / div>
< div class =white>< / div>
< / div>
$(div.container div)。each(function(){
var color = $(this).attr(class);
$(this).css({backgroundColor:color});
});
我试图随机化订单,所以 div.container div
处于任何随机位置,这意味着它开始的位置不同。并且div必须保留在 div.container中
我试过
http://jsfiddle.net/UgX3u/32/
http://jsfiddle.net/UgX3u/20/ 和更多的功能,我发现在网络上,但非工作
我怎么能得到div的随机顺序显示
试试这个:
< pre $
$(div.container div)。sort(function(){
return Math.random()* 10> 5?1:-1;
$ b $ color = $ t.attr(class);
$ t.css({ backgroundColor:color})。appendTo($ t.parent());
});
.sort
适用于jQuery :
$。fn.sort = [] .sort
由于它不像其他jQuery方法那样执行,因此没有记录。这确实意味着它可能会发生变化,但我怀疑它会改变。为避免使用未记录的方法,您可以这样做:
http: //jsfiddle.net/UgX3u/37/
var collection = $(div.container div) 。得到();
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());
});
I have this jQuery and HTML http://jsfiddle.net/UgX3u/30/
<div class="container">
<div class="yellow"></div>
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
<div class="pink"></div>
<div class="orange"></div>
<div class="black"></div>
<div class="white"></div>
</div>
$("div.container div").each(function(){
var color = $(this).attr("class");
$(this).css({backgroundColor: color});
});
I am trying to randomise the order, so the div.container div
is in any random position, meaning not the same position it started. and the div must remain within the div.container
I have tried http://jsfiddle.net/UgX3u/32/ http://jsfiddle.net/UgX3u/20/ and more functions I found on the net but non are working
how can I get the div's to display in a random order
Try this:
$("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:
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() );
});
这篇关于jQuery,随机div顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!