【问题标题】:How to complete remove div?如何完成删除div?
【发布时间】:2021-06-08 01:34:53
【问题描述】:

我用 jQuery 创建了一个 div 元素:

$(document.body).append('<div id="test"></div>');

然后显示消息并在 10 秒后删除 div

$('test').html('SUCCESS!');
setTimeout(function(){
  $('#test').remove();
}, 10000);

然后检查div删除是否完成,控制台日志显示信息:

$(window).on('scroll', function () {
    if($('#test').length === 0){
      console.log('DIV removed!');
    } else {
      console.log('DIV not removed!!!')
    }
}

当我向上或向下滚动消息时显示“DIV 未删除!!!”。

为什么我的 div 没有被删除?

【问题讨论】:

    标签: javascript html jquery css ecmascript-6


    【解决方案1】:

    您在将其添加到 DOM 后立即运行“检查”。 “移除”只会在未来 10 秒后发生。

    我已更改您的示例以演示两个代码放置差异。您可以单击运行并观察行为。

    我还将它从 10 秒更改为 2 秒以加快演示速度。

    简而言之,您应该在删除行本身之后运行要在删除后运行的代码。

    $(document.body).append('<div id="test"></div>');
    
    $('#test').html('SUCCESS!');
    setTimeout(function(){
      $('#test').remove();
      
      // Runs LATER
      if($('#test').length === 0){
        console.log('[LATER] DIV removed!');
      } else {
        console.log('[LATER] DIV not removed!!!')
      }
    }, 2000);
    
    // Immediately, Befor setTimeout has run
    if($('#test').length === 0){
      console.log('[IMMEDIATE] DIV removed!');
    } else {
      console.log('[IMMEDIATE] DIV not removed!!!')
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 谢谢,但我想在滚动页面显示此消息时
    【解决方案2】:

    // onload 
    $(function(){
      // set height 1000px  on body for support event scroll
      $('body').css('height','1000px');
      
      // append
      $(document.body).append('<div id="test"></div>');
      $('#test').html('SUCCESS!');
      
      // remove in 2s
      setTimeout(function(){
        $('#test').remove();
      }, 2000);
      
      // scroll event
      $(window).on('scroll', function () {
          if($('#test').length === 0){
            console.log('DIV removed!');
          } else {
            console.log('DIV not removed!!!')
          }
      });
    
    });
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 1970-01-01
      • 2013-03-07
      • 2019-03-11
      • 2021-08-10
      • 2014-01-09
      • 1970-01-01
      • 2017-11-27
      • 2011-06-02
      相关资源
      最近更新 更多