几秒钟后淡出并移除一个元素

17

为什么在$.fadeout的回调函数中无法删除元素?

例如:

$(".background-blackout").fadeOut('slow', function(){
    // Remove all the layer.
        $(this).remove();
}));


alert($('.background-blackout').length);
// return 1

这段代码可以不使用回调函数:

$(".background-blackout").fadeOut('slow', function(){

}).remove();

alert($('.background-blackout').length);
// return 0.

但是它在元素完全淡出之前移除了该元素。所以我认为我应该在几秒钟后调用remove()?

那么我如何使用remove()来实现这个效果呢?

我尝试了这个方法,但是图层不会被删除:

$(".background-blackout").fadeOut('slow', function(){
});


setTimeout(function(){
    $(".background-blackout").remove(); 
},2000);


alert($('.background-blackout').length);
// returns 1.

4
你是否注意到你的alert()fadeOut完成之前就触发了? ;) - RightSaidFred
1个回答

38

您的答案几乎正确,但是您需要在回调函数内测试元素是否存在,如下所示:

$(".background-blackout").fadeOut('slow', function(){
  $(this).remove();
  // alert( $('.background-blackout').length );
  console.log( $('.background-blackout').length );
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接