1

我对如何随机播放元素有点沮丧(因为我在其中存储了数据,仅仅更改文本是不够的)。我正在尝试洗牌兄弟元素,所以我应该使用 .before 和 .after。这是我当前的代码

function shuffle() {
    var children = $("#paren").children();
    randIndex = randomFromTo(0, arr.length - 1);

    for(i = 0; i < children.length; i++) {
        //But obviously I can't retrieve a specific child like this
        $("#parent nth-child("+randIndex+")").before(children.i);
    }
}
function randomFromTo(from, to){
    return Math.floor(Math.random() * (to - from + 1) + from);
}
4

2 回答 2

0

将孩子们作为数组抓取,随机播放并再次附加它们。由于它们是相同的引用,附加实际上会移动它们。

var parent = $('ul');

var children = parent.children().get().sort(function() {
    return Math.random() - 0.5;
});

parent.append(children);

https://tinker.io/54968

于 2012-10-06T16:10:34.780 回答
0

构建一个元素数组,打乱数组,然后重新添加元素。

function shuffle(parent) {
    var container = document.getElementById(parent),
        children = container.children,
        length = children.length, i,
        tmparr = [];
    for( i=0; i<length; i++) tmparr[i] = children[i];
    tmparr.sort(function() {return 0.5-Math.random();});
    for( i=0; i<length; i++) container.appendChild(tmparr[i]);
}

注意完全没有 jQuery。我还对您的函数进行了参数化,以便您可以使用它来调用它,shuffle("paren")而不是使用单一用途的函数。

于 2012-10-06T16:11:32.527 回答