[英]Randomize children elements on load
I want to randomize the children elements of any <div>
, <ul>
on load with javascript. 我想随机加载任何
<div>
, <ul>
的子元素。 I am searching for the best approach to do it. 我正在寻找实现这一目标的最佳方法。 Can some one help?
可以帮忙吗?
Suppose i have a <ul>
with 5 <li>
elements. 假设我有一个带有5个
<li>
元素的<ul>
。 On load i want the <li>
elements to appear in random order. 在加载时,我希望
<li>
元素以随机顺序出现。
Quicky out of my head: 快点走出我的脑海:
<ul>
with detach
detach
删除<ul>
中的所有项目 <ul>
again. <ul>
插入元素。 Also take a look at this question: randomize div elements 还看一下这个问题:将div元素随机化
Here's how I did it (JSFiddle example here: http://jsfiddle.net/LNvqr/2/ ) 这是我的操作方法(此处是JSFiddle示例: http : //jsfiddle.net/LNvqr/2/ )
If you use jQuery and have HTML similar to this: 如果您使用jQuery并具有类似于以下内容的HTML:
<div>
<ul id="rndList">
<li id="itemOne">one</li>
<li id="itemTwo">two</li>
<li id="itemThree">three</li>
<li id="itemFour">four</li>
<li id="itemFive">five</li>
</ul>
</div>
Then you could simply use .detach to remove and store the array of the <li>
elements. 然后,您可以简单地使用.detach删除并存储
<li>
元素的数组。
Next, with a copy of the array, use Math.random()
to generate a (pseudo)random integer between 0 and one less than the size of the array. 接下来,使用数组的副本,使用
Math.random()
生成一个(伪)随机整数,该整数在0到小于数组大小的整数之间。 Use this as the random index to be copied from the original (ordered) list in to the new (randomly-ordered) one. 将其用作要从原始(有序)列表复制到新(无序)列表中的随机索引。
Remove the randomly-chosen element from the original array on each iteration and choose a new random one until all elements have been re-inserted: 在每次迭代中从原始数组中删除随机选择的元素,然后选择一个新的随机元素,直到重新插入所有元素:
function shuffleList() {
var origList = $("#rndList li").detach();
var newList = origList.clone();
for (var i = 0; i < newList.length; i++) {
//select a random index; the number range will decrease by 1 on each iteration
var randomIndex = randomInt(newList.length - i);
//place the randomly-chosen element into our copy and remove from the original:
newList[i] = origList.splice(randomIndex, 1);
//place the element back into into the HTML
$("#rndList").append(newList[i]);
}
}
function randomInt(maxNum) { //returns a random integer from 0 to maxNum-1
return Math.floor(Math.random() * maxNum);
}
You can achieve this with below code: 您可以使用以下代码实现此目的:
$(function () {
var parent = $("#parent-container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.