简体   繁体   中英

Proper deleting HTML DOM nodes

I'm trying to create a star shining animation.

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);
}

It works fine until I uncomment the following code which is supposed to regulate star count:

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

Then it stops to work as if the created stars are not removed (the first 5 stars blink then nothing happens). Why do the jQuery selector select them after gameArea.removeChild(star); ? Isn't it enough to remove them from the parent node?

Browser: Google Chrome 17.

Regards,

Change the commented out lines to

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

to keep the ShowStars recursion going.

I see a workaround: do not create stars dynamically, but insert them in HTML ( <img id="star1"> ... <img id="starN"> , where N is total count) then light and put out the existing nodes. Nevertheless, I'd like to understand, what's wrong with removing nodes in the question above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM