问题
I am hiding multiple items like this:
$('#item1,#item2,#item3').hide('slow',function() {
console.log('hidden');
});
Problem is that this logs four times. For reasons beyond my control I cannot use a common class on each element. Is there a nice jquery-ish way to make this handler only fire after the last item has hidden? (or the first, since they should be virtually simultaneous)
Also, the elements will be hidden and shown many times, so whatever is used to limit the handler call will have to be reset afterwards.
I can obviously put some kind of boolean in the handler, but I was hoping for a cleaner solution.
回答1:
You could use $.when() and deferred.done()
$.when($('#item1,#item2,#item3').hide('slow')).done(function() {
console.log('hidden');
});
Simple working example
回答2:
What about...
$('#item1,#item2,#item3').hide('slow', function() {
if ($(this).is(':last')){
// code
}
});
EDIT: It doesn't work because the $(this)
context changes inside of the hide()
callback. Try caching selector first:
var $els = $('#item1,#item2,#item3');
$els.hide('slow', function(e) {
if ($(this).is($els.last())){
alert('test');
}
});
回答3:
You could use a queue (although @ManseUK's answer looks like the right way to do it now)
$({})
.queue(function(next){
$('#item1, #item2, #item3').hide('slow', next);
})
.queue(function(){
console.log('hidden');
});
demo at http://jsfiddle.net/duzB8/
回答4:
var counter = 0;
$('#item1,#item2,#item3').hide('slow',function() {
counter++;
if ( counter == 3 ){ console.log('hidden'); }
});
来源:https://stackoverflow.com/questions/10225948/how-to-hide-multiple-items-but-only-call-the-handler-once