【问题标题】:How to randomize the order in which lists are displayed in HTML? [duplicate]如何随机化列表在 HTML 中显示的顺序? [复制]
【发布时间】:2014-05-23 06:03:36
【问题描述】:

我有一个这样的 HTML 列表:

<ul>
<li>This is an item.</li>
<li>This is another item.</li>
<li>This is yet another item.</li>
</ul>

如何在每次加载文档时以随机顺序显示这些项目?

【问题讨论】:

  • 你试过了吗?
  • 需要更多信息。您总是可以使用ul.magic(random),这也应该可以解决问题。订购它们可以在 javascript 或服务器端完成。
  • ul.magic(random) 是否添加到 &lt;ul&gt; 中?

标签: javascript html css


【解决方案1】:

这里有答案javascript - shuffle HTML list element order

var ul = document.getElementById("item");

for (var i = ul.children.length; i >= 0; i--) { ul.appendChild(ul.children[Math.random() * i | 0]); }

【讨论】:

    【解决方案2】:

    添加这个javascript:

    var ul = document.getElementById("list");
    for (var i = ul.children.length; i >= 0; i--)
    ul.appendChild(ul.children[Math.random() * i | 0]);
    

    DEMO

    (这个答案最初是由Alexey Lebedev针对这个问题提供的:javascript - shuffle HTML list element order

    【讨论】:

    • 至少给出适当的归属
    • 是的,我知道它是重复的;我找到了答案here
    • @Satpal 是的,我已经添加了它。谢谢你告诉我。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2017-11-21
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多