how to hide multiple items but only call the handler once?

☆樱花仙子☆ 提交于 2019-12-24 00:52:16

问题


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

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