更新时间:2023-11-23 14:51:28
查看这个问答帖子。我喜欢这个解决方案通过用户 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
在评论中告诉我 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.