简体   繁体   中英

Only deleting the oldest element created using jQuery, after a timer

I have a ship fly over whenever a button is clicked, although at the moment it deletes all of the the ships on screen, not the oldest one created.

(function (el) {
  setTimeout(function () {
    el.children().remove('.ship');
  }, 5000);
}($('#saleShipHolder').append("<div class='ship' id='saleShip'></div>")));

It creates the ship, appends the ship element but the problem arises when the ship gets removed as it removes all of them on screen, not the oldest one. Sorry as I find this difficult to explain.

Thankyou in advance.

Well for starters, each "ship" has the same id, which it should not have. Also since they all have the same class, its going to find them all.

A simple approach would be to splice the newest ship element onto an array,and on your timeout .pop() off the oldest entry, and remove it .

Why not encapsulate the ship ?

(function (el) {
    var ship = $("<div class='ship' id='saleShip'></div>");

    el.append(ship);

    setTimeout(function () {
      ship.remove();
    }, 5000);

}($('#saleShipHolder')));

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