开发者

jquery callback not working

Can anyone tell me what I'm doing wrong in this jquery script?

$(document).ready(function() { 
    $("a.book").click(function() {
        $(this).parent().next('div').slideToggle('slow', function(){开发者_JS百科
            $(this).toggleClass('bookopen');
        });
    });
});

I want the div to toggle, and then afterwards I want the element $a.book to change to $a.bookopen. But when I write the code above the toggle doesn't work. If I remove the callback function toggleClass the the slideToggle works just fine.

Any ideas? I appreciate your help.


Your this reference in the inner callback is to the div that's being toggled, not the a that triggered it. You could close over a reference to it,

$(document).ready(function() { 
    $("a.book").click(function() {
        var $a = $(this);
        $(this).parent().next('div').slideToggle('slow', function(){
            $a.toggleClass.('bookopen');
        });
    });
});

or you could navigate back to it from jQuery methods from the div:

$(document).ready(function() { 
    $("a.book").click(function() {
        $a.parent().next('div').slideToggle('slow', function(){
            $(this).prev('whatever').find('a.book').toggleClass('bookopen');
        });
    });
});

Note that this depends on the element structure.


I suspect the reference to this is not what you want for the callback function. Set a breakpoint on that line to check.


In addition to the changes harpo mentioned, I think this line of code:

$a.toggleClass.('bookopen');

should be this:

$a.toggleClass('bookopen');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜