简体   繁体   中英

How to know when a function jQuery has completed

I have a piece of jQuery and I can't get it done. I have 2 bulletproof vest images. When a button is clicked, 1 will show up. When another is clicked, all vests have to be hidden again first. Now the vests both show up and then 1 disappears.

Here is my example: http://bykwien.nl/soldier/voorbeeld.html

Full preview on JSFiddle: http://jsfiddle.net/8DPCf/

$('#vest1').click(function(){
            $('.vest').addClass('hide', function(){
                $('.vest1').removeClass('hide');
            })
        });

        $('#vest2').click(function(){
            $('.vest').addClass('hide', function(){
                $('.vest2').removeClass('hide');
            })
        });

Just remove the callbacks will make the whole thing work, see here:

http://jsfiddle.net/8DPCf/1/

$('#vest2').click(function(){
    $('.vest').addClass('hide', function(){
        $('.vest2').removeClass('hide');
    })
});

becomes

$('#vest2').click(function(){
    $('.vest').addClass('hide');
    $('.vest2').removeClass('hide');
});

According to the jQuery documentation , the addClass method has no callback parameter, which it also doesn't need because it doesn't do anything asynchronically.

Quick Fix

I don't think you need to use any callback function for this, just do the 2 calls sequentially like so:

$('#vest1').click(function(){
    $('.vest').addClass('hide');
    $('.vest1').removeClass('hide');
});

$('#vest2').click(function(){
    $('.vest').addClass('hide');
    $('.vest2').removeClass('hide');
});

Here is a working example

Advanced Solution

In order to make it more generic, allowing for x number of vests you could create a single event handler and determine the vest class using the id of the clicked button...

Change your button HTML like so (added class):

<div class="item-checkbox vest-button" id="vest1"></div>
<div class="item-checkbox vest-button" id="vest2"></div>

And your javascript as follows:

//add event to all vest elements, and use this to determine which one is clicked
$('.vest-button').click(function(){
    $('.vest').addClass('hide');
    var className = '.' + $(this).attr("id");
    $(className).removeClass('hide');
});

Here it is in action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM