2011-10-10 83 views
0

我想隨意使用javascript加載任何<div>,<ul>的子元素。我正在尋找最好的方法來做到這一點。有人可以幫忙嗎?隨機加載兒童元素

假設我有元素。在加載時,我希望<li>元素以隨機順序出現。

+1

你可以更具體嗎? –

+0

[用jQuery隨機化一個div元素序列](http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery) –

回答

1

這裏是我做到了(的jsfiddle這裏的例子:http://jsfiddle.net/LNvqr/2/

如果你使用jQuery,並有HTML與此類似:

<div> 
    <ul id="rndList"> 
     <li id="itemOne">one</li> 
     <li id="itemTwo">two</li> 
     <li id="itemThree">three</li> 
     <li id="itemFour">four</li> 
     <li id="itemFive">five</li> 
    </ul>  
</div> 

然後,您可以簡單地使用.detach刪除並存儲<li>元素的數組。
接下來,使用數組的副本,使用Math.random()生成0到1之間的(僞)隨機整數,該整數小於數組的大小。將其用作從原始(有序)列表複製到新(隨機排序)列表的隨機索引。
從在每次迭代原數組中取出隨機選擇的元素,然後選擇一個新的隨機一個,直到所有元件已經被重新插入:

function shuffleList() { 
    var origList = $("#rndList li").detach(); 
    var newList = origList.clone(); 

    for (var i = 0; i < newList.length; i++) { 
     //select a random index; the number range will decrease by 1 on each iteration 
     var randomIndex = randomInt(newList.length - i); 

     //place the randomly-chosen element into our copy and remove from the original: 
     newList[i] = origList.splice(randomIndex, 1); 

     //place the element back into into the HTML 
     $("#rndList").append(newList[i]); 
    } 
} 

function randomInt(maxNum) { //returns a random integer from 0 to maxNum-1 
    return Math.floor(Math.random() * maxNum); 
} 
0

可以用下面的代碼實現這一點:

$(function() { 
    var parent = $("#parent-container"); 
    var divs = parent.children(); 
    while (divs.length) { 
     parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
    } 
});