現在、リスト項目をランダムにソートする次のコードがあります。
var $ul = $('#some-ul-id');
$('li', $ul).sort(function(){
return ( Math.round( Math.random() ) - 0.5 )
}).appendTo($ul);
しかし、それに対するより良い解決策はありますか?
現在、リスト項目をランダムにソートする次のコードがあります。
var $ul = $('#some-ul-id');
$('li', $ul).sort(function(){
return ( Math.round( Math.random() ) - 0.5 )
}).appendTo($ul);
しかし、それに対するより良い解決策はありますか?
この質問と回答のスレッドを見てください。私はユーザー経由でこのソリューションが好き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;
};
編集:以下の使用方法。
<li>
各 '.member' 内のすべての要素をランダム化するには<div>
:
$('.member').randomize('li');
each のすべての子をランダム化するには<ul>
:
$('ul').randomize();
別の編集: データまたは添付されたリスナーが要素に接続されており、それらがランダム化されている場合、それらを所定の位置に保持するという主な利点の代わりに使用できるakalata
コメントで私に知らせました。リスナーを放り出すだけです。detach()
remove()
detach()
remove()
また、Googleで検索して1つのコードに出くわしたような質問にも固執しました。このコードを自分の用途に合わせて変更します。また、15 秒後にリストをシャッフルします。
<script>
// This code helps to shuffle the li ...
(function($){
$.fn.shuffle = function() {
var elements = this.get()
var copy = [].concat(elements)
var shuffled = []
var placeholders = []
// Shuffle the element array
while (copy.length) {
var rand = Math.floor(Math.random() * copy.length)
var element = copy.splice(rand,1)[0]
shuffled.push(element)
}
// replace all elements with a plcaceholder
for (var i = 0; i < elements.length; i++) {
var placeholder = document.createTextNode('')
findAndReplace(elements[i], placeholder)
placeholders.push(placeholder)
}
// replace the placeholders with the shuffled elements
for (var i = 0; i < elements.length; i++) {
findAndReplace(placeholders[i], shuffled[i])
}
return $(shuffled)
}
function findAndReplace(find, replace) {
find.parentNode.replaceChild(replace, find)
}
})(jQuery);
// I am displying the 6 elements currently rest elements are hide.
function listsort(){
jQuery('.listify_widget_recent_listings ul.job_listings').each(function(index){
jQuery(this).find('li').shuffle();
jQuery(this).find('li').each(function(index){
jQuery(this).show();
if(index>=6){
jQuery(this).hide();
}
});
});
}
// first time call to function ...
listsort();
// calling the function after the 15seconds..
window.setInterval(function(){
listsort();
/// call your function here 5 seconds.
}, 15000);
</script>
この解決策がお役に立てば幸いです....楽しい時間をお過ごしください..