说明[Randoming List]

时间:2017-12-13 09:43:50

标签: javascript html list

javascript随机列表.. 我不明白它是如何工作的,请帮我解释一下javascript的工作原理。

<ul id="name">
    <li>Sunday</li>
    <li>Monday</li>
    <li>Tuesday</li>
    <li>Wednesday</li>
    <li>Thursday</li>
    <li>Friday</li>
    <li>Saturday</li>
</ul>

     <script>

var ul = document.getElementById("name"), 
    temp = ul.cloneNode(true), 
    i = temp.children.length + 1;

while( i-- > 0 )
    temp.appendChild( temp.children[Math.random() * i |0] );

ul.parentNode.replaceChild(temp, ul);

</script>

2 个答案:

答案 0 :(得分:1)

//saving <ul> element wiсh id is 'name' to the ul variable
var ul = document.getElementById("name"),  
    //cloning this ul and all its child elements to the temp variable; 
    //cloneNode(true) means deep copy, cloneNode(false) copies only the node 
    temp = ul.cloneNode(true),   
    // we will start from the end of the child nodes array and go down          
    i = temp.children.length + 1; 

//at each iteration we will decrement i and compare it to 0
while (i-- > 0)
    //while this condition is true we take a random node from the child elements array;
    //here we use Math.random() to generate a random number from 0 to 1, 
    //multiply it by i to get a number from 0 to i and then use bitwise OR with 0
    //to convert this floating point number to an integer (see below for more details);
    //and then we append this random child to the temp; if a node already exists
    //in the DOM, then appendNode will remove it before appending, so we just replace
    //the nodes in random order
    temp.appendChild(temp.children[Math.random() * i | 0]);

//and finally we replace the old ul with a new one
ul.parentNode.replaceChild(temp, ul);

有关按位OR的更多信息,请查看here

答案 1 :(得分:0)

首先,您get the ul tag, which id is nameul = document.getElementById("name")


clone the nodetemp = ul.cloneNode(true)
您将获得li拥有的ul代码的i = temp.children.length + 1个代码:x--(+1代表循环播放时为0),
while循环将递减x((i--) > 0)并检查它是否大于0:temp.appendChild( temp.children[Math.random() * i |0] ),并将一个random子项附加到克隆节点:ul.parentNode.replaceChild(temp, ul)
最后,您只需replace all your ul child with your temp (cloned) childsint