Q
随机加载儿童元素
0
A
回答
2
Quicky了我的头:
- 与
detach
- 存储数组把它们删除在
<ul>
的所有项目。 - Shuffle that array
- 再次在
<ul>
中插入元素。
也来看看这个问题:randomize div elements
1
这里是我做到了(的jsfiddle这里的例子:http://jsfiddle.net/LNvqr/2/)
如果你使用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>
然后,您可以简单地使用.detach删除并存储<li>
元素的数组。
接下来,使用数组的副本,使用Math.random()
生成0到1之间的(伪)随机整数,该整数小于数组的大小。将其用作从原始(有序)列表复制到新(随机排序)列表的随机索引。
从在每次迭代原数组中取出随机选择的元素,然后选择一个新的随机一个,直到所有元件已经被重新插入:
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);
}
0
可以用下面的代码实现这一点:
$(function() {
var parent = $("#parent-container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
相关问题
- 1. 加载jQuery儿童
- 2. 访问jquery儿童元素
- 3. 清除儿童元素
- 4. 儿童JSON元素Angularjs
- 5. 查找isDirty()儿童元素
- 6. 动态加载儿童班?
- 7. 使用Hpricot获取儿童元素
- 8. 不尊重儿童元素的高度
- 9. 不要选择儿童类元素(Jsoup)
- 10. Bootstrap儿童元素高度100%
- 11. 获取儿童元素的高度
- 12. 儿童元素重复FlipView内
- 13. 可订购儿童元素排序组
- 14. JQuery命名动态元素和儿童
- 15. 使用XML儿童验证XHTML元素
- 16. 从jQuery获取儿童元素的.text()
- 17. 改变儿童元素的值
- 18. html click,除了元素AND儿童
- 19. 目标儿童元素,但不是被点击的元素
- 20. 围绕主要元素的儿童包裹元素。 JQLite
- 21. 如何选择儿童元素,直到元素中找到
- 22. Angular 4儿童路由器不加载
- 23. 从JSON中加载jsTree儿童
- 24. 儿童主题的style.css未加载
- 25. 聚合物儿童DOM加载
- 26. 添加基于价值的父元素类儿童 - angular2
- 27. 解析儿童Simplexml儿童
- 28. 儿童内部角儿童
- 29. 向元素添加随机边距
- 30. Angular 4延迟加载路由 - 儿童不加载
你可以更具体吗? –
[用jQuery随机化一个div元素序列](http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery) –