I have an array list of 100 objects that I want to randomly append on to the screen.
for (var i = 0; i < theobject.length; i++) {
var item = theobject[Math.floor(Math.random()*theobject.length)];
$('.container').append('<div class="theitem"> item.themessage </div>')
}
Ok so my goal is to append five of them at a time on the screen and then randomly replace one by one of those 5 by the next on the "qued list". The one that fades out will be removed from the DOM, also from the object list so it wont get placed again. Any suggestions? Thanks a ton!
答案 0 :(得分:1)
以下是如何做到这一点:
// foo.cppm
module foo;
export void test() {
}
方法清除并设置5个元素之一的不透明度animate
方法创建承诺,并链接在动画准备就绪时执行的promise
回调then
在选择和淡化下一个项目之前引入一些时间。delay
运算符实现循环数组遍历代码:
%
&#13;
// Utility function
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
// Some sample data
var theobject = ["Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","Ut","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","Duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","eu","fugiat","nulla","pariatur","Excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"]
.map(s => ({ themessage: s}));
// 1. Shuffle the array
shuffle(theobject);
// 2. Add the first 5 elements on the page
for (var i = 0; i < 5; i++) {
$('<div>').addClass("theitem").text(theobject[i].themessage).appendTo($('.container'));
}
// 3. Asynchronous loop to select one of those 5 and replace with next from shuffled array
(function loop(i) {
var j = Math.floor(Math.random() * 5);
$('.container>.theitem').eq(j).animate({ opacity: 0 }).promise().then(function () {
return $(this).text(theobject[i].themessage).animate({ opacity: 1 }).delay(500).promise();
}).then(function () {
loop((i + 1) % theobject.length);
});
})(5);
&#13;