我需要在父 div 中添加一个子 div,然后在 x 秒内删除子 div。
可以将多个子 div 添加到父 div 中。
识别和删除子 div 的最佳方法是什么?
$("#parent_div").prepend("<div>"+msg+"</div>");
最佳答案
通过保留对它的引用:
function doTheChildDivThing() {
var child = $("<div>" + msg + "</div>");
$("#parent").prepend(child);
setTimeout(function() {
child.remove();
}, 1000);
}
<小时/>
在下面回复您的评论:
why delay() (instead of setTimeout) is not working in that case?
delay
与效果队列一起使用。 remove
不是与效果相关的方法。您当然可以将 delay
与 effects methods 之一一起使用。不过,就像 slideUp
一样。然后,您可以在effects方法的完成回调中删除子级,如下所示:
function doTheChildDivThing() {
var child = $("<div>" + msg + "</div>");
$("#parent").prepend(child);
child.delay(1000).slideUp(function() {
child.remove();
});
}
关于jquery - 添加 DOM 元素然后将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817422/