javascript - 随机化 li 项并卡住多个

标签 javascript jquery random

我需要随机化 5-n 里项目的列表,并为特定位置的 1-5 项目设置,例如,我有

  1. 一个
  2. b
  3. c
  4. d
  5. e
  6. f

我想随机化最后 4 个并放在 li[0] 字母 D 和 li[2] 字母 F 上 结果:

  1. d
  2. f
  3. c
  4. b
  5. 一个
  6. e

这是我的代码。我哪里错了?谢谢!

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

最佳答案

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>

关于javascript - 随机化 li 项并卡住多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232470/

相关文章:

javascript - 目标为 ="_blank"的表单 - 新窗口和加载页面

javascript - 如果它有数据但类型或值不正确

javascript - Material 组件 : Keeping Menu "Open" when clicking inside

java - 如何实现一副纸牌?

javascript - jQuery 指定内部 html

javascript - 每个起始字母只匹配一个单词

javascript - jQuery 视差导航不会滚动到目标

jquery - .click 函数后获取值 jQuery 具有动态内容的 jQuery

c - 将系统时间用于随机数生成器种子

c++ - 给定种子和偏移量生成下一个伪随机值