此选择器在超时内不起作用

时间:2018-12-20 16:47:44

标签: javascript jquery

获得了一个隐藏的div,该div必须在几秒钟的延迟后显示,并根据其高度获得样式。这些隐藏的div是动态的。因此,它们每个都有一个独特的高度。找不到隐藏的div的高度,因此,我在删除隐藏元素的类之后添加了高度计算。现在,当我使用实际的类或删除超时时,脚本似乎正在运行。使用(this)内部超时时-没有任何反应,并且控制台中没有错误。

if ($(".bubble")[0]) {
  $(".bubble").each(function() {
    setTimeout(function() {
      $(this).removeClass("hide");
      var bubblehe = $(this).height();
      $(this).css('top', bubblehe);
    }, 2000)

  });

  $(document.body).click(function() {
      $(".bubble").addClass("hide");
    }
  }
.hide (display:none;)

2 个答案:

答案 0 :(得分:2)

setTimeout有它自己的上下文,因此其中的this不会是您的节点

if($(".bubble")[0]) {       
        $(".bubble").each(function(){
            const self = this;
            setTimeout(function(){
                $(self).removeClass("hide");
                var bubblehe = $(this).height();
                $(self).css('top',bubblehe);
            }, 2000)

        });

        $(document.body).click(function(){
            $(".bubble").addClass("hide");
        }
}

答案 1 :(得分:0)

//cache your repeated selector
var $bubble = $('.bubble');

//length > 0 is truthy
if ($bubble.length) {
  $bubble.each(function() {
    //cache your jQuery instantiation
    //this solves the changing value of this in the timeout
    //and stops duplicate jQuery instantiation
    var $this = $(this);
    
    setTimeout(function() {
      $this
        .removeClass("hide")
        .css('top', $this.height());
    }, 2000);
  });

  $(document.body).click(function() {
      $bubble.addClass("hide");
  });
}
html,body { min-width: 640px; min-height: 480px; }
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bubble hide">Bubble 1</div>
<div class="bubble hide">Bubble 2</div>