随机化锂项目和冻结多个
问题描述:
我需要随机的5-N李项的列表和1-5项的具体设置到位,例如,我有随机化锂项目和冻结多个
- 一个
- b
- ç
- d
- Ë
- ˚F
我想随机最后4装上的Li [0]信d和李[2]字母F 结果:
- d
- ˚F
- Ç
- b
- 一个
- Ë
这是我的代码。我错在哪里?谢谢!
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>
随机性非常简单,但我不清楚它是如何在逻辑上应该知道治疗* d *和* F *特殊,因为该列表可以是N长。 – Taplar
Math.random返回一个介于0和1之间的浮点数,这是非常不可能的,随机* i将完全等于0,1或2.通常人们使用'Math.floor(Math.random()* i)'返回一个0到i之间的整数 - 1 – James
我需要像“Apple”和“Orange”这样的字符串来选择li的位置,其余的随机选择 – Malasuerte94