【问题标题】:Jquery .remove() does not update DOMJquery .remove() 不更新 DOM
【发布时间】:2015-07-23 06:14:54
【问题描述】:

我正在尝试使用 .remove() jQuery 方法从 DOM 中删除一个元素

基本上我正在解析一个列表并删除某些元素。然后紧接着,我重新解析列表以对其余元素进行一些处理。

但是列表大小的简单打印输出给我的印象是要过滤掉的元素没有被删除

$list = $(".elements_list");
alert( $list.size());
$list.each(function(){
  if ( $(this).data("quantity") == 0)
  {
    $(this).slideUp(1000,function(){
      $(this).remove();
    });
  }
});
change_background_colors();

在这种处理之后,我调用了另一个开头有以下代码的函数:

function change_background_colors() {    
  $list = $(".elements_list");
  alert($list.size());
  ...
}

我在删除元素之前和之后得到相同大小的列表...

我的方法有问题吗?

谢谢!

【问题讨论】:

  • 上下文是什么意思?抱歉,我是 jQuery/Javascript 新手...
  • 他的意思是你去remove的时候检查this的值。
  • 如果你在动画完成之前调用它,元素仍然存在。告诉我们您将第二次尺寸检查放在哪里
  • 我编辑了我的问题以显示我在哪里放置尺寸警报

标签: javascript jquery dom


【解决方案1】:

如果您在 setTimeOut 函数中调用尺寸警报,您将看到

$list = $(".elements_list");
alert($list.size());
$list.each(function () {
    if ($(this).data("quantity") == 0) {
        $(this).slideUp(1000, function () {
            $(this).remove();

        });
    }
});

setTimeout(function () {
    $list = $(".elements_list");
    alert($list.size());
}, 2000);

JSFiddle:

https://jsfiddle.net/upkkLq2m/2/

【讨论】:

  • 我建议使用这种方法来延迟第二次计数,因为它比我的编辑更简单
【解决方案2】:

元素直到 1000 毫秒过去且动画完成后才会被移除。等到那时计算元素。

编辑:这是延迟到所有动画完成的更复杂的方法:

$list = $(".elements_list");
var n = 0;
$list.each(function(){
  if ( $(this).data("quantity") == 0) {
    n = n + 1; // one more callback to wait for
    $(this).slideUp(1000,function(){
      $(this).remove();
      n = n-1;
      checkIfAllDone();
    });
  }
});
function checkIfAllDone(){
  if(n===0){ // be sure that n was declared in the same scope as this function
    change_background_colors();
  }
}

【讨论】:

  • 我宁愿指出(解释)OP 来计算动画回调中的元素 - 在 remove... 之后
  • 如果您看到代码中的更改,您会看到我在 slideUp 回调之外打印出尺寸。
  • 如何等待所有的 slideUps 完成?
猜你喜欢
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
相关资源
最近更新 更多