【问题标题】:Using .hide with .remove function in JQuery does not remove item from the DOM在 JQuery 中使用 .hide 和 .remove 函数不会从 DOM 中删除项目
【发布时间】:2014-05-18 08:31:39
【问题描述】:

我正在尝试使用 JQuery 删除一个元素,但我仍然想要 .hide 函数的转换。我想出了这个解决方案:

$("#box-"+likeid).hide('slow', function(){ $("#box-"+likeid).remove(); });

但是,在此之后,我想遍历索引重要的项目列表(我使用 .each)。所有这些项目都具有相同的类,因此我遍历具有该类的项目并从中查找索引。

我发现,当我使用上述隐藏/删除解决方案时,该项目仍被视为具有索引的项目。但是,当我只使用普通的 .remove 时,它​​不会被计算在内,它会按照我想要的方式运行。

但回到前面的一点,我喜欢 .hide 过渡。有没有解决的办法?谢谢你。

编辑:

这是完整的 Jquery 函数:

$(".remove-item").click(function(event) {

      event.preventDefault();

      var id = $(this).find("i.fa-times").attr('id');

      var likeid = id.replace( /^\D+/g, '');

      var elem = $("#box-"+likeid).hide('slow', function() { $("#box-"+likeid).remove(); });

      $('.spacer').remove();

      $('.boxBg').not(elem).each(function() {
              $(this).removeClass('last');

              if (($(this).index() + 1) % 4 == 0){

                $(this).addClass('last');
                $('<div class="spacer"></div>').insertAfter($(this));
              }


      });

});

基本上,我希望每四个元素都有一个表示新行的“last”类。当一个被删除时,我想更新它。但是,在使用它时,它不会将 last 分配给正确的。即使使用您在下面分享的这种方式,它也是一次性的。

【问题讨论】:

  • 将循环移动到回调中。
  • @undefined,您应该将其发布为答案。效果很好。
  • 那么将 .each 循环移动到函数中?
  • @user1072337 完全正确。
  • 是的,这是一个异步操作,回调在600(slow)毫秒后执行。

标签: javascript jquery


【解决方案1】:

这是因为回调函数在 600 毫秒后执行(),您可以将 each 循环移动到回调中,或者使用 not 方法从集合中排除元素:

// `hide` returns the current collection
var $elem = $("#box-"+likeid).hide('slow', function(){ $(this).remove(); });

$collection.not($elem).each(function(i) {
    // ...
});

【讨论】:

  • 不幸的是,这些都没有达到预期的效果......我会草拟一下我正在尝试做的事情。
猜你喜欢
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 2013-04-24
  • 2015-06-10
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多