2012-10-06 73 views
0

我对如何洗牌要素感到有些沮丧(因为我有数据存储在它们中,只是简单地改变文本就不够)。我试图洗牌兄弟元素,所以我应该使用.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); 
} 
+0

那么它有什么问题?它不起作用吗? 你没有说明你的问题... –

回答

0

抓住孩子们的阵列,随机播放并再次追加。由于它们是相同的参考,所以追加将实际移动它们。

var parent = $('ul'); 

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

parent.append(children); 

https://tinker.io/54968

0

构建元件的阵列,洗牌阵列,然后reappend的元素。

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")来调用它,而不是使用单一功能。

+0

谢谢你的伟大答案! – Pawna

相关问题