嘗試使用數組中的項目創建元素,該元素每隔一秒隨機選擇一個數組,直到數組爲空。當我不將元素追加到dom中時,我很難過爲什麼我的函數可以工作,但是一旦我添加到dom中,數組變得越來越大,並最終導致dom崩潰。從數組創建新元素,直到數組每秒都爲空
我的計劃是最終創建一個具有圖像的新對象,隨機xy位置的css,然後使用對象值向dom添加一個新元素。
基本上我試圖添加隨機圖像到dom每秒,並讓他們動畫進出,直到數組爲空。
任何幫助將不勝感激,謝謝。
"load": function(){
var imgArray = ['brain', 'mitochondria', 'microscope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
window.setInterval(function(){
var imgItem;
if(imgArray.length >= 1) {
var index = Math.floor(Math.random()*imgArray.length);
console.log(imgArray[index]); // Log the item
imgItem = (imgArray[index]); // Log the item
imgArray.splice(index, 1); // Remove the item from the array
// $('form').append('<img class="img-animation" src="img/science/'+ imgItem +'.svg" alt="'+ imgItem +'">');
}
}, 1000);
},
這是當我不追加新的圖像控制檯:
home.js:11 beaker
home.js:11 dropper
home.js:11 microscope
home.js:11 beaker-2
home.js:11 atom
home.js:11 brain
home.js:11 scientist
home.js:11 cell
home.js:11 mitochondria
如果我新的圖像添加到DOM最終會崩潰,循環的推移永遠這是沒有意義的對我來說。
你是否考慮過在每次迭代中記錄數組的內容,然後它可能會顯示你爲什麼/哪裏出錯。例如:if(imgArray.length && iterationLimit)'(例如初始化'iterationLimit = 10'後)爲了防止無限循環在'if'中使用另一個變量,它只允許10次迭代;在這兩種情況下,'0'都是錯誤的,所以一旦數字中的任何一個達到'0','if'就會成爲'false'並停止)。 –
我也很好奇,看看這個「加載」回調在更新DOM後被重新調用。 –
我使用Meteor作爲我的框架 –