如何随机排序列表项? [英] How to randomly sort list items?
问题描述
我目前有这个代码随机排序列表项:
I currently have this code that randomly sorts list items:
var $ul = $('#some-ul-id');
$('li', $ul).sort(function(){
return ( Math.round( Math.random() ) - 0.5 )
}).appendTo($ul);
但是,还有更好的解决方案吗?
However, is there any better solution for that?
推荐答案
查看这个问答帖子。我喜欢这个解决方案通过用户 gruppler
:
Look at this question and answer thread. I like this solution via the user gruppler
:
$.fn.randomize = function(selector){
var $elems = selector ? $(this).find(selector) : $(this).children(),
$parents = $elems.parent();
$parents.each(function(){
$(this).children(selector).sort(function(){
return Math.round(Math.random()) - 0.5;
// }). remove().appendTo(this); // 2014-05-24: Removed `random` but leaving for reference. See notes under 'ANOTHER EDIT'
}).detach().appendTo(this);
});
return this;
};
编辑:以下使用说明。
随机化每个'.member'< div>
< li> 元素>:
To randomize all <li>
elements within each '.member' <div>
:
$('.member').randomize('li');
随机化每个< ul> $ c $的所有孩子c>:
$('ul').randomize();
另一个编辑: akalata
在评论中告诉我<可以使用code> detach()代替 remove()
,主要好处是,如果连接了任何数据或附加的侦听器一个元素,它们是随机的, detach()
将它们保持在原位。 remove()
只会抛弃听众。
ANOTHER akalata
has let me know in the comments that detach()
can be used instead of remove()
with the main benefit being if any data or attached listeners are connected to an element and they are randomized, detach()
will keep them in place. remove()
would just toss the listeners out.
这篇关于如何随机排序列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!