Randomize a unordered list [duplicate]

青春壹個敷衍的年華 提交于 2019-12-12 10:17:09

问题


Possible Duplicate:
javascript - shuffle HTML list element order

After a little bit of help. After something quite simple, but can't seem to find a way of doing it myself.

I've got a dynamic unordered list being generated from some back end code, (not under my control). The list can be anything from 9 tags up to 100+. They are returned in an order, as defined by the backend code. Using jQuery/javascript I would like to be able to randomize the order of the li tags without having any of them repeat.

My my list would currently look something like this:

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
</ul>

回答1:


Exactly what you want to do is described on the jQuery Forums.

$(document).ready(function(){
      $('ul').each(function(){
            // get current ul
            var $ul = $(this);
            // get array of list items in current ul
            var $liArr = $ul.children('li');
            // sort array of list items in current ul randomly
            $liArr.sort(function(a,b){
                  // Get a random number between 0 and 10
                  var temp = parseInt( Math.random()*10 );
                  // Get 1 or 0, whether temp is odd or even
                  var isOddOrEven = temp%2;
                  // Get +1 or -1, whether temp greater or smaller than 5
                  var isPosOrNeg = temp>5 ? 1 : -1;
                  // Return -1, 0, or +1
                  return( isOddOrEven*isPosOrNeg );
            })
            // append list items to ul
            .appendTo($ul);            
      });
});

Example: http://jsbin.com/upuju3/2



来源:https://stackoverflow.com/questions/8225582/randomize-a-unordered-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!