Web*_*ner 36 html javascript html-lists
我有一个清单:
<ul>
<li>milk</li>
<li>butter</li>
<li>eggs</li>
<li>orange juice</li>
<li>bananas</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
使用javascript如何随机重新排序列表项?
Ale*_*dev 76
var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);
}
Run Code Online (Sandbox Code Playgroud)
这是基于Fisher-Yates shuffle,并利用了这样一个事实:当你追加一个节点时,它会从它的旧位置移开.
即使在巨大的列表(10万个元素)上,性能也在改变分离副本的10%以内.
小智 11
简单地说,像这样:
JS:
var list = document.getElementById("something"),
button = document.getElementById("shuffle");
function shuffle(items)
{
var cached = items.slice(0), temp, i = cached.length, rand;
while(--i)
{
rand = Math.floor(i * Math.random());
temp = cached[rand];
cached[rand] = cached[i];
cached[i] = temp;
}
return cached;
}
function shuffleNodes()
{
var nodes = list.children, i = 0;
nodes = Array.prototype.slice.call(nodes);
nodes = shuffle(nodes);
while(i < nodes.length)
{
list.appendChild(nodes[i]);
++i;
}
}
button.onclick = shuffleNodes;
Run Code Online (Sandbox Code Playgroud)
HTML:
<ul id="something">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button id="shuffle" type="button">Shuffle List Items</button>
Run Code Online (Sandbox Code Playgroud)
演示:http://jsbin.com/itesir/edit#preview