0

我用 AJAX 加载页面。该页面包含以下代码(对于 div 的移动动画,#1 将其向左移动,#2 将其再次向后移动)

#1 
$('#flipper').click(function () { 
      $(".l-l").animate({ "left": -267 }, 600, function () {
             $('#flipper').addClass('flipper-h'); 
       });
});

#2
$('#flipper.flipper-h').die(); //to prevent .live() event bubbling. I guess
$('#flipper.flipper-h').live('click', function () { 
    $(".l-l").animate({ "left": 0 }, 600, function () {
            $('#flipper').removeClass('flipper-h'); 
    });
});

使用该代码我有一些问题:

1)在第一页加载后,代码#2在动画开始前有一点卡顿

2)在第二个(以及更多)页面加载后,#2 代码不会触发。为什么 ?

编辑

我注意到代码#2 被无限次调用(这很奇怪)。但是,我已经通过代码修复了 1) 的情况:

$('#flipper').click(function () {
        if(!$(this).hasClass('flipper-h')) {
                $(".l-l").animate({ "left": -267 }, 600, function () {
                $('#flipper').addClass('flipper-h');
            }); 
        } else {
            $(".l-l").animate({ "left": 0 }, 600, function () {
                $('#flipper').removeClass('flipper-h');
             });
       }
});

但问题2)仍未解决。有任何想法吗 ?

4

1 回答 1

1

EDIT3: Consider these two codes:

http://jsfiddle.net/2zEZT/2/

http://jsfiddle.net/2zEZT/3/

In first example, when you use remove button, elements are removed with elements that looks like same, but they are not. Events are lost.

In second one, elements are removed but click event is binded again after that...

EDIT2: Based on your edit, try to use this function instead. It could behaves better...

$('#flipper').click(function () {
    if ($(this).hasClass('flipper-h')) {
        $(this).removeClass('flipper-h');
        $(".l-l").animate({
            "left": 0
        }, 600);
    } else {
        $(this).addClass('flipper-h');
        $(".l-l").animate({
            "left": -267
        }, 600);
    }
});

EDIT: I suggest that you still use jQuery 1.7 so I did a little investigation.

At first, you put event onclick on the #flipper.

Then you call die on #flipper.flipper-h element. Which should destroy all live events.

After that, you made a live event on #flipper.flipper-h element, which means that all elementes that exists and will exists will have this event.

Now first click: animation left: -267 happens, then callback does #flipper becomes #flipper.flipper-h, then live event is binded to new #flipper.flipper-h,

Second click: animation left: -267 happens, but it was already there, so nothing happens at all then callback does #flipper becomes #flipper.flipper-h, so nothing happens again, now event is still bubbling, so second animation left: 0 is triggered after 600ms (this is probably your freeze) now callback removes .flipper-h

Now I dont know how exactly does your ajax works, but it seems that die function removes live event from #flipper forever. So it can't be triggered anymore...

die function doesnt prevent bubbling. It removes live events. return false or event.stopPropagation does

于 2013-11-07T12:38:05.413 回答