jQuery帮助循环回调jQuery

时间:2013-07-22 16:38:27

标签: jquery

帮助循环回调jQuery

my Fiddle

错误循环按钮2

第1步:点击Button1 =>回调Button2

步骤2:CLick Button2 =>回调Button2 +回调Button2

第3步:点击Button3 =>回调Button2 +回调Button2 +回调Button2

.....

步骤n:点击按钮* n * =>回电Button2 * n


帮助修复:

点击Button1 n =>回调Button2 * 1

谢谢!

1 个答案:

答案 0 :(得分:0)

您正在事件中绑定事件。如果你考虑一下,如果你这样做,那么你所描述的是不可避免的......每次点击按钮一次都会将另一个点击事件绑定到button2,依此类推......

我已经重构了你的代码,以实现你想要的,同时具有足够的灵活性,以便在需要时进行扩展。

JSBin fork

$(function() {
    var body = $('body'),
        button2 = body.find('#b2');

    var events = {
        b1 : function(event) {
            // Unbind this click event to avoid event stacking
            body.off('click', '#b1', events.b1);

            // Fade in the second button and bind its event
            button2.fadeIn('fast', function() {
                body.on('click', '#b2', events.b2);
            });
        },
        b2 : function(event) {
            // Unbind button2 event whilst managing its click logic
            alert('Button 2 clicked');
            body.off('click', '#b2', events.b2);

            // Hide button 2 and rebind the event to button 1
            button2.fadeOut('fast', function() {
                body.on('click', '#b1', events.b1);
            );
        }
    };

    // Bind the click event to button1
    body.on('click', '#b1', events.b1);
});