jQuery: can the empty() method be given a duration?
In jQuery, can the empty() method be given a duration, such that the object fades to empty over a period of time (for example, 500 milliseconds)?
Here is the current code:
$('#object_to_be_emptied').开发者_如何学Pythonempty();
No. Fade the content out, then empty it when the fade is complete.
$('#object_to_be_emptied').children().fadeOut(500, function() {
$('#object_to_be_emptied').empty();
});
This code unfortunately calls empty
as many times as there are elements under #object_to_be_emptied
. If you are using jQuery > 1.6, you can get round this with the $.Deferred
support for animations:
$('#object_to_be_emptied').children().fadeOut(500).promise().then(function() {
$('#object_to_be_emptied').empty();
});
The other two answers suggest using $('#object_to_be_emptied').children().fadeOut()
, but it is actually a bad idea to use .children()
because this will cause an animation to be applied to each of the child elements within your containing element (killing performance), and therefore execute the animation complete callback once for each element within object_to_be_emptied
. With more than just a couple of elements, this will turn into a real problem.
Instead, just apply the animation to the containing element, remembering to call .fadeIn()
after you've repopulated it and want to show it again.
$('#object_to_be_emptied').fadeOut(500, function() {
$(this).empty();
});
Also note that I've used this
in the callback function – jQuery sets this
to be the DOM element which is the target of the callback function; in this case, object_to_be_emptied
. Using this
saves some typing and makes code changes down the line easier.
you're probably looking for something like:
$('#object_to_be_emptied').children().fadeOut(500,function(){
$('#object_to_be_emptied').empty()
});
精彩评论