randSortItem.js

随机排列显示 items

by alanoy

HTML

<div id="test">
    <div class="testItem item1">1000</div>
    <div class="testItem item2">2000</div>
    <div class="testItem item3">3000</div>
    <div class="testItem item4">4000</div>
    <div class="testItem item5">5000</div>
</div>

CSS

#test { color: white; }
.item1 { background-color: red; }
.item2 { background-color: green; }
.item3 { background-color: brown; }
.item4 { background-color: black; }
.item5 { background-color: blue; }

JavaScript

$(function() {
    randomItem({
        parentId: "test"
    });
});
/* @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 = $('#' + args.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));
        });
    }
}