2012-06-29 49 views
0

我正試圖創建一顆閃爍的星星動畫。正確刪除HTML DOM節點

function ShowStars() 
{ 
    //if ($('img.star').length > 5) 
    // return; 

    var x = Math.floor(Math.random() * gameAreaWidth) - 70; 
    var y = Math.floor(Math.random() * gameAreaHeight); 

    var star = document.createElement("img"); 
    star.setAttribute("class", "star"); 
    star.setAttribute("src", imagesPath + "star" + GetRandom(1, 3) + ".png"); 
    star.style.left = x + "px"; 
    star.style.top = y + "px"; 
    gameArea.appendChild(star); 
    // Light. 
    setTimeout(function() { star.setAttribute("class", "star shown"); }, 0); 
    // Put out. 
    setTimeout(function() { star.setAttribute("class", "star"); }, 2000); 
    // Delete. 
    setTimeout(function() { gameArea.removeChild(star); }, 4000); 

    setTimeout(function() { ShowStars(); }, 500); 
} 

,直到我去掉下面的代碼這是應該調節星級計數它工作正常:

//if ($('img.star').length > 5) 
// return; 

然後它停止工作,因爲如果不刪除創建的星(第5星閃爍然後沒有任何反應)。爲什麼jQuery選擇器在gameArea.removeChild(star);之後選擇它們?將它們從父節點中刪除不夠嗎?

瀏覽器:谷歌瀏覽器17.

問候,

回答

1

註釋掉線更改爲

if ($('img.star').length > 5) { 
    setTimeout(function() { ShowStars(); }, 500); 
    return; 
} 

保持ShowStars遞歸去。

+0

糟糕!是的,這是原因。 – noober

0

我看到一個解決辦法:不要動態創建的明星,但在HTML(<img id="star1"> ... <img id="starN">,其中N是總數)將其插入,然後點亮並放出現有的節點。不過,我想了解,在上面的問題中刪除節點有什麼問題。