如何知道函数jQuery何时完成

时间:2014-02-06 15:01:53

标签: javascript jquery

我有一块jQuery,我无法完成它。我有2个防弹背心图像。单击按钮时,将显示1。当点击另一个背心时,必须首先再次隐藏所有背心。现在背心出现了,然后1消失了。

以下是我的示例:http://bykwien.nl/soldier/voorbeeld.html

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');
            })
        });

2 个答案:

答案 0 :(得分:2)

只需删除回调即可使整个过程完成,请参阅此处:

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

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

变为

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

根据jQuery documentationaddClass方法没有回调参数,它也不需要,因为它不会异步执行任何操作。

答案 1 :(得分:2)

快速修复

我认为你不需要使用任何回调函数,只需按顺序执行2次调用:

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

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

Here is a working example

高级解决方案

为了使它更通用,允许x个背心,你可以创建一个单独的事件处理程序,并使用点击按钮的id确定背心类......

像这样更改按钮HTML(添加类):

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

你的javascript如下:

//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

相关问题