jQuery:append() 对象,使用 delay() 删除()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3655627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:50:30  来源:igfitidea点击:

jQuery: append() object, remove() it with delay()

jqueryappenddelay

提问by matt

what's wrong with that?

那有什么问题?

$('body').append("<div class='message success'>Upload successful!</div>");
$('.message').delay(2000).remove();

I want to append a success message to my html document, but only for 2sec. After that the div should be deleted again.

我想在我的 html 文档中附加一条成功消息,但只有 2 秒。之后应该再次删除div。

what am i doing wrong here?

我在这里做错了什么?

regards

问候

回答by Nick Craver

Using setTimeout()directly (which .delay()uses internally) is simpler here, since .remove()isn't a queued function, overall it should look like this:

setTimeout()直接使用(在.delay()内部使用)在这里更简单,因为.remove()它不是排队函数,总体来说应该是这样的:

$('body').append("<div class='message success'>Upload successful!</div>");
setTimeout(function() {
  $('.message').remove();
}, 2000);

You can give it a try here.

你可以在这里试一试

.delay()is for the animation (or whatever named) queue, to use it you'd have to do something like:

.delay()用于动画(或任何命名的)队列,要使用它,您必须执行以下操作:

$("<div class='message success'>Upload successful!</div>").appendTo('body')
  .delay(2000).queue(function() { $(this).remove(); });

Which works, here...but is just overkill and terribly inefficient, for the sake of chaining IMO. Normally you'd also have to call dequeue or the next function as well, but since you're removing the element anyway...

这在这里有效......但为了链接IMO ,这只是矫枉过正且效率极低。通常,您还必须调用 dequeue 或 next 函数,但是由于您无论如何都要删除元素......

回答by Viktor Kruglikov

I think that correct way of doing that is to use jQuery queue method:

我认为这样做的正确方法是使用 jQuery 队列方法:

    $("<div class='message success'>Upload successful!</div>")
        .appendTo('body')
        .delay(2000)
        .queue(function() {
            $(this).remove();
        });

回答by WSkid

Maybe I'm using an outdated jQuery, but none of the methods suggested in other answers seem to work for me. According to http://api.jquery.com/delay/, delay is for animation effects.

也许我使用的是过时的 jQuery,但其他答案中建议的方法似乎都不适合我。根据http://api.jquery.com/delay/,延迟用于动画效果。

Using setTimeout()however, works nicely for me:

setTimeout()但是,使用对我来说效果很好:

$('body').append("<div class='message success'>Upload successful!</div>"); 
setTimeout(function(){
    $(".message").remove();
}, 2000);

回答by Strelok

And just for kicks, you could do the following, using delay:

只是为了踢球,您可以使用延迟执行以下操作:

$('body').append("<div class='message success'>Upload successful!</div>");
$('.message').show('fast').delay(2000).hide('fast')
$('.message').remove();