有个项目需要用到随机排列按钮,写完顺便记录下 snippet。需求大概就是一堆按钮然后随机显示就行了,还是较简单的。
先看 Demo,再贴下 js 代码:
/* @author: Alan Ouyang
* @param: {Object} args include: *parentId{String}
* @description: 随机显示 items
* -------------------------------------------------------*/
function randOrd() {
return ( Math.round(Math.random()) - 0.5 );
}
function randomItem(args) {
var $parent = $('#' + ars.parentId),
$item = $parent.children(),
itemLength = $item.length;
if (itemLength > 1) {
$item.remove();
var indices = [];
for (var i = 0; i < itemLength; i++) { indices[indices.length] = i; }
indices = indices.sort(randOrd);
$.each(indices, function(j, k) { $parent.append($item.eq(k)); });
}
}
* @param: {Object} args include: *parentId{String}
* @description: 随机显示 items
* -------------------------------------------------------*/
function randOrd() {
return ( Math.round(Math.random()) - 0.5 );
}
function randomItem(args) {
var $parent = $('#' + ars.parentId),
$item = $parent.children(),
itemLength = $item.length;
if (itemLength > 1) {
$item.remove();
var indices = [];
for (var i = 0; i < itemLength; i++) { indices[indices.length] = i; }
indices = indices.sort(randOrd);
$.each(indices, function(j, k) { $parent.append($item.eq(k)); });
}
}