随机化无序列表 [英] Randomize a unordered list
问题描述
之后一点帮助。经过一些非常简单的事情,但似乎无法找到自己做的方法。
After a little bit of help. After something quite simple, but can't seem to find a way of doing it myself.
我有一个动态无序列表是从一些后端代码生成的, (不在我的控制之下)。该列表可以是9个标签到100多个标签之间的任何内容。它们按照后端代码定义的顺序返回。使用jQuery / javascript我希望能够随机化li标签的顺序而不重复它们。
I've got a dynamic unordered list being generated from some back end code, (not under my control). The list can be anything from 9 tags up to 100+. They are returned in an order, as defined by the backend code. Using jQuery/javascript I would like to be able to randomize the order of the li tags without having any of them repeat.
我的列表目前看起来像这样:
My my list would currently look something like this:
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
</ul>
推荐答案
你想要做的就是< a href =http://forum.jquery.com/topic/random-order-of-elements> jQuery论坛。
$(document).ready(function(){
$('ul').each(function(){
// get current ul
var $ul = $(this);
// get array of list items in current ul
var $liArr = $ul.children('li');
// sort array of list items in current ul randomly
$liArr.sort(function(a,b){
// Get a random number between 0 and 10
var temp = parseInt( Math.random()*10 );
// Get 1 or 0, whether temp is odd or even
var isOddOrEven = temp%2;
// Get +1 or -1, whether temp greater or smaller than 5
var isPosOrNeg = temp>5 ? 1 : -1;
// Return -1, 0, or +1
return( isOddOrEven*isPosOrNeg );
})
// append list items to ul
.appendTo($ul);
});
});
示例: http ://jsbin.com/upuju3/2
这篇关于随机化无序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!