2012-10-06 153 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