[英]Manipulating DOM in componentDidMount() without setTimeout
[英]Manipulating new DOM elements generated through loop with setTimeout
假設我是出於學習目的而制作游戲。
游戲如下 :
- 有一個棋盤(這是我的網格:坐標數組)
- 還有一些,我們稱它們為在棋盤上隨機移動的斑點 。
- 移動時, 斑點可以復制自己 。
我的目標 :
是使用循環和setTimeout()逐個移動每個Blob 。
為什么要使用setTimeout?
因為我不希望他們同時在棋盤上移動 :)
我的問題 :
當blob復制時 ,新的DOM元素將與Jquery一起注入到網頁上。 但是 , 循環已經完成工作,並且由於setTimeout , 當循環為每個blob分配新位置時 , 新的DOM元素就不存在了 。
結果 :
只有游戲開始時出現的斑點才在那里獲得新的位置 。
我的代碼示例(簡化):
for (var cycles = 1; cycles <= this.cycles + 1; cycles ++)
{
for (var t = 0; t < CHARACTERS_LIST.length; t++) // t => Character Type
{
if (CHARACTERS_LIST[t].length != 0)
{
for (var i = 0; i < CHARACTERS_LIST[t].length; i++) // i => Index
{
// Moves the blob on the chessboard
//
// ***********************************************
MoveCharacter(t, i);
}
}
}
}
//********************************************************************
var loop = 1;
function MoveCharacter(t, i){
CHARACTERS_LIST[x][y].moveAndDupicate(); // Duplicates if Math.ramdon succeeds
LOG.characterHistory(); // Log/Log.js
setTimeout( function(x, y) { return function() {
if (!CHARACTERS_LIST[x][y].isBorn) {
if (x == 0) {
$('#blue-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
} else if (x == 1) {
$('#green-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
} else if (x == 2) {
$('#red-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
} else if (x == 3) {
$('#special-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
}
} else {
CHARACTERS_LIST[x][y].isBorn = false;
var _blob, _inner;
_blob = document.createElement('div');
_blob.className = "blob";
_inner = document.createElement('div');
_inner.className = "inner";
_blob.appendChild(_inner);
if(CHARACTERS_LIST[x][y] instanceof BlueBlob){
_inner.style = "background-color:#52DE71;";
_blob.style = "top:" + CHARACTERS_LIST[x][y].posY + "em;"
+ "left:" + CHARACTERS_LIST[x][y].posX + "em;";
$('#blue-blob').append(_blob);
} else if (CHARACTERS_LIST[x][y] instanceof GreenBlob){
_inner.style = "background-color:#5299DE;";
_blob.style = "top:" + CHARACTERS_LIST[x][y].posY + "em;"
+ "left:" + CHARACTERS_LIST[x][y].posX + "em;";
$('#green-blob').append(_blob);
}
}
}}(t, i), 100*loop);
loop++;
}
所以...
- 就像我說的那樣,只有游戲開始時最初存在的blob才獲得新的位置。
- 每個周期 , CHARACTERS_LIST []被更新。
- 問題似乎在這里: .blob:nth-child('+(y + 1)+')') ,因為尚未創建此元素。 ( 我認為... )
我似乎找不到問題,但我敢肯定,這只是上面代碼中的一些小問題!
問題是我試圖使用DOM元素和Jquery來實現所有這些功能(效率不高)。 我使用了HTML畫布,並且一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.