我问过如何在JS here中重新整理一些已创建的div的顺序。一个人回答了我,但是当我按照他告诉我的方法进行操作时,某些div不会显示,而其他div会出现两次。如何在刷新时自动将订单改组而不出现这些问题?谢谢!
答案 0 :(得分:0)
“某些元素出现两次” 表示您随机播放出错了。如果可以粘贴完整代码。我不知道您是如何洗牌的,但是请尝试以下操作,
var dbUsers = firebase.database().ref('...');
dbUsers.on('value', gotData1, errData1);
function gotData1(data) {
var users = data.val();
var keys = Object.keys(users);
// Shuffle 'keys' here
shuffledKeys = shuffle(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var name = users[k].name;
var div = document.createElement('div');
div.setAttribute('class', 'div');
var usersPre = document.createElement('pre');
usersPre.textContent = name;
div.appendChild(usersPre);
};
}
function shuffle(array) {
var currentIndex = array.length, randomIndex;
var temporaryValue;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}