2012-06-29 52 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是总数)将其插入,然后点亮并放出现有的节点。不过,我想了解,在上面的问题中删除节点有什么问题。