JavaScript - случайный порядок элементов списка HTML - PullRequest
34 голосов
/ 15 августа 2011

У меня есть список:

<ul>
    <li>milk</li>
    <li>butter</li>
    <li>eggs</li>
    <li>orange juice</li>
    <li>bananas</li>
</ul>

Используя javascript, как я могу изменить порядок элементов списка случайным образом?

Ответы [ 5 ]

69 голосов
/ 15 августа 2012
var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
    ul.appendChild(ul.children[Math.random() * i | 0]);
}

Это основано на Fisher-Yates shuffle и использует тот факт, что при добавлении узла он перемещается со своего старого места.перестановки отдельной копии даже в огромных списках (100 000 элементов).

http://jsfiddle.net/qEM8B/

10 голосов
/ 16 августа 2011

Проще говоря, вот так:

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;

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>

Демонстрация: http://jsbin.com/itesir/edit#preview

1 голос
/ 30 октября 2013
    var list = document.getElementById("something");
    function shuffleNodes() {
        var nodes = list.children, i = 0;
        nodes = Array.prototype.sort.call(nodes);
        while(i < nodes.length) {
           list.appendChild(nodes[i]);
           ++i;
        }
    }
    shuffleNodes();
0 голосов
/ 02 февраля 2017

Вот очень простой способ перемешать с JS:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});

http://www.w3schools.com/js/js_array_sort.asp

0 голосов
/ 14 сентября 2016

Исходя из ответа @ Алексея Лебедева, если вы предпочитаете функцию jQuery, которая перемешивает элементы, вы можете использовать эту функцию:

$.fn.randomize = function(selector){
  var $elems = selector ? $(this).find(selector) : $(this).children();
  for (var i = $elems.length; i >= 0; i--) {
    $(this).append($elems[Math.random() * i | 0]);
  }

  return this;
}

И затем вызывать ее так:

$("ul").randomize();        //shuffle all the ul children
$("ul").randomize(".item"); //shuffle all the .item elements inside the ul
$(".my-list").randomize(".my-element"); //shuffle all the .my-element elements inside the .my-list element.
...