2011-10-10 86 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]); 
    } 
});