簡體   English   中英

如何隨機排序列表項?

[英]How to randomly sort list items?

我目前有這個隨機排序列表項的代碼:

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;
};

編輯:下面的使用說明。

隨機化每個 '.member' <div>所有<li>元素:

$('.member').randomize('li');

隨機化每個<ul>所有孩子:

$('ul').randomize();

akalata編輯: akalata在評論中告訴我可以使用detach()而不是remove()主要好處是如果任何數據或附加的偵聽器連接到元素並且它們是隨機的, detach()將保留它們到位。 remove()只會把聽眾扔出去。

我也堅持在谷歌上搜索並遇到一個代碼的這些問題。 我修改此代碼以供我使用。 我還包括 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>

希望這個解決方案有幫助......祝你工作愉快......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM