随机化li项并冻结多个

时间:2017-11-10 23:06:29

标签: javascript jquery random

我需要随机化一个5-n li项目列表,并为特定地点设置1-5项目,例如,我有

  1. 一个
  2. B'/ LI>
  3. C
  4. d
  5. ë
  6. ˚F
  7. 我想把最后4个随机化并放在li [0]字母D和li [2]字母F上 结果:

    1. d
    2. ˚F
    3. C
    4. B'/ LI>
    5. 一个
    6. ë
    7. 这是我的代码。我哪里错了?谢谢!

          var ul = document.querySelector('ul');
          for (var i = ul.children.length; i >= 0; i--) {
      
          if(ul.children.innerHTML == "XXX") {
              ul.appendChild(ul.children[0]);
          }
          if(ul.children.innerHTML == "XXXX") {
              ul.appendChild(ul.children[1]);
          }
          if(ul.children.innerText == "XX") {
              ul.appendChild(ul.children[2]);
          } else {
              ul.appendChild(ul.children[generateRandom(i) | 0]);
          }
      }
      
      
      function generateRandom(i) {
          var num = Math.random() * i | 0;
          return (num === 0 || num === 1 || num === 2) ? generateRandom(i) : num;
      }
      

1 个答案:

答案 0 :(得分:1)

var $test = $('#test');
var $li = $test.children();

while ($li.length > 0) {
  //pick a random li from the variable
  var $next = $li.eq( Math.floor( Math.random() * 10 * $li.length ) % $li.length );
  //move it to the end of ul
  $test.append($next);
  //remove the li from our variable so it won't be found again
  $li = $li.not($next);
}

//move the f to the top, so when we move the d to the top it will be second
$test.prepend($test.children().filter(function(){ return this.innerHTML === 'f'; }));
//move the d to the top
$test.prepend($test.children().filter(function(){ return this.innerHTML === 'd'; }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="test">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
  <li>i</li>
  <li>j</li>
  <li>k</li>
</ul>