【问题标题】:javascript - shuffle HTML list element orderjavascript - 随机播放 HTML 列表元素顺序
【发布时间】:2011-10-27 13:21:23
【问题描述】:

我有一个清单:

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

使用 javascript 如何随机重新排序列表项?

【问题讨论】:

标签: javascript html html-lists


【解决方案1】:

简单地说,像这样:

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

【讨论】:

  • 如果有人能提出更轻量级的解决方案,我将不胜感激并接受他们的回答。谢谢!
  • 我不会将 26 行代码称为“大”。您将很难找到更小的东西。
  • 为什么 HTML 不需要引用脚本(显然在 IE 中除外)?
  • 26 行代码太疯狂了。 Alexey Lebedev 的回答更好。
【解决方案2】:
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 个元素)上,性能也比洗牌分离的副本的性能差 10%。

http://jsfiddle.net/qEM8B/

【讨论】:

  • 对于大量的项目,建议在 JS 中洗牌该元素的副本,然后将其原样复制回 DOM。演示 - jsbin.com/jiboxuru/1/edit
  • @vsync 感谢您的编辑,但我已将其回滚,因为循环不需要将“+ 1”添加到 children.length。向下舍入 length 给出最大的索引。
  • 字符数相同 ;) 但你是对的。 jsbin.com/jiboxuru/3/edit
【解决方案3】:
    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();

【讨论】:

    【解决方案4】:

    基于没有@Alexey Lebedev 的回答,如果您更喜欢一个随机播放元素的 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.
    

    【讨论】:

    • 这个创建了重复项
    • @Glapa 你能举个例子吗?
    【解决方案5】:

    这里有一个非常简单的用 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

    【讨论】:

    【解决方案6】:

    我正在寻找一个原型函数。也许这对某人有帮助。

    Element.prototype.shuffleChildren = function() {
      for (var i = this.children.length; i >= 0; i--) {
        this.appendChild(this.children[Math.random() * i | 0]);
      }
    };
    
    document.querySelector('body').shuffleChildren();
    

    【讨论】:

      【解决方案7】:

      使用这个:

      function htmlShuffle(elem) {
          function shuffle(arr) {
              var len = arr.length;
              var d = len;
              var array = [];
              var k, i;
              for (i = 0; i < d; i++) {
                  k = Math.floor(Math.random() * len);
                  array.push(arr[k]);
                  arr.splice(k, 1);
                  len = arr.length;
              }
              for (i = 0; i < d; i++) {
                  arr[i] = array[i];
              }
              return arr;
          }
          var el = document.querySelectorAll(elem + " *");
          document.querySelector(elem).innerHTML = "";
          
          let pos = [];
          for (let i = 0; i < el.length; i++) {
              pos.push(i);
          }
          
          pos = shuffle(pos);
          for (let i = 0; i < pos.length; i++) {
              document.querySelector(elem).appendChild(el[pos[i]]);
          }
      }
      
      htmlShuffle("ul");
      <ul>
          <li>milk</li>
          <li>butter</li>
          <li>eggs</li>
          <li>orange juice</li>
          <li>bananas</li>
      </ul>

      【讨论】:

        猜你喜欢
        • 2023-01-23
        • 2015-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-26
        • 2012-03-22
        • 2020-12-10
        • 1970-01-01
        相关资源
        最近更新 更多