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

北战南征 提交于 2019-11-26 15:52:18

问题


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.

what am i doing wrong here?

regards


回答1:


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

$('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:

$("<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...




回答2:


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

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



回答3:


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.

Using setTimeout() however, works nicely for me:

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



回答4:


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();


来源:https://stackoverflow.com/questions/3655627/jquery-append-object-remove-it-with-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!