简体   繁体   English

在计时器之后仅删除使用jQuery创建的最旧的元素

[英]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. 对于初学者来说,每个“船”都有相同的ID,不应该具有相同的ID。 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 . 一种简单的方法是将最新的ship元素splice到数组上,并在超时时将.pop()从最旧的条目中删除,并将其删除。

Why not encapsulate the ship ? 为什么不封装船呢?

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

    el.append(ship);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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