我对如何改变元素感到有点沮丧(因为我有数据存储在其中,只是改变文本是不够的)。我试图改变兄弟元素,所以我应该使用.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);
答案 1 :(得分: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")
来调用它,而不是使用单一功能。