2017-11-10 62 views
0

我需要隨機的5-N李項的列表和1-5項的具體設置到位,例如,我有隨機化鋰項目和凍結多個

  1. 一個
  2. b
  3. ç
  4. d
  5. Ë
  6. ˚F

我想隨機最後4裝上的Li [0]信d和李[2]字母F 結果:

  1. d
  2. ˚F
  3. Ç
  4. b
  5. 一個
  6. Ë

這是我的代碼。我錯在哪裏?謝謝!

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

隨機性非常簡單,但我不清楚它是如何在邏輯上應該知道治療* d *和* F *特殊,因爲該列表可以是N長。 – Taplar

+0

Math.random返回一個介於0和1之間的浮點數,這是非常不可能的,隨機* i將完全等於0,1或2.通常人們使用'Math.floor(Math.random()* i)'返回一個0到i之間的整數 - 1 – James

+0

我需要像「Apple」和「Orange」這樣的字符串來選擇li的位置,其餘的隨機選擇 – Malasuerte94

回答

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>