jQuery 5 秒后删除新 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4364219/
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
remove new div after 5 seconds
提问by eyalb
i want to add a div and after 5 seconds remove it. i tried
我想添加一个 div 并在 5 秒后将其删除。我试过
$("#mainContentTD").prepend("<div style='color: #038a00; padding-bottom:10px;'>Your detailes where sucsesfuly... </div>").delay(5000).remove("this:first-child");
回答by Sarfraz
You can use setTimeout
like this:
你可以这样使用setTimeout
:
setTimeout(function(){
$('#divID').remove();
}, 5000);
The 5000 (ms) means 5 seconds. You should replace divID
with your own div/element id.
5000 (ms) 表示 5 秒。你应该divID
用你自己的 div/element id替换。
You can make sure that the div exists first using length
:
您可以首先使用length
以下方法确保 div 存在:
setTimeout(function(){
if ($('#divID').length > 0) {
$('#divID').remove();
}
}, 5000)
回答by jensgram
The .delay()
method only works with methods that utilize the standard effect queue or a custom queue.
该.delay()
方法仅适用于利用标准效果队列或自定义队列的方法。
The
.delay()
method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay()
is not a replacement for JavaScript's nativesetTimeout
function, which may be more appropriate for certain use cases.
该
.delay()
方法最适合在排队的 jQuery 效果之间延迟。因为它是有限的——例如,它不提供取消延迟的方法——.delay()
不能替代 JavaScript 的本机setTimeout
函数,后者可能更适合某些用例。
I.e., you could either use setTimeout()
: (Demo)
即,您可以使用setTimeout()
:( Demo)
var $elm = $("<div style='color: #038a00; padding-bottom:10px;'>Your detailes where sucsesfuly... </div>");
$("#mainContentTD").prepend($elm);
setTimeout(function() {
$elm.remove();
}, 5000);
Or, you could use a effect method to remove to element: (Demo)
或者,您可以使用效果方法删除元素:(Demo)
$("#mainContentTD")
.prepend("<div style='color: #038a00; padding-bottom:10px;'>Your detailes where sucsesfuly... </div>")
.children(':first')
.delay(5000)
.fadeOut(100);