开发者

Why isn't this callback resolving properly in jQuery?

I have this code:

    $(document).ready(function(){
        $(".links a").click(function(e){
            var toLoad = "products.html #" + this.id;
            $('#block').fadeTo('fast',0,loadContent);

            function loadContent() {  
                    $('#block').load(toLoad,'',showNewContent())  
                }  
            function showNewContent() {  
            开发者_如何学C        $('#block').fadeTo('slow',100);  
                }
            e.preventDefault();
        });

    });

The idea is:

  • click on a link to trigger (check!)
  • the "block" div fades to 0 (check!)
  • the content is switched out (check!)
  • the "block" div fades back 100 (whoops!)

The behavior I see is that the div fades out, then pops back with new content as soon as the fadeOut is completed.

Any thoughts on this?


Change this:

function loadContent() {
  $('#block').load(toLoad,'',showNewContent())  
} 

to

function loadContent() {
  $('#block').load(toLoad,'',showNewContent)  
} 

To explain: you're calling the function immediately (and passing its non-existent return as to load()) whereas you want to pass the function (rather than what it returns) as the callback.

Note: also, fadeTo() states:

The opacity to fade to (a number from 0 to 1).

so you should probably change:

function showNewContent() {  
  $('#block').fadeTo('slow',100);  
}

to

function showNewContent() {  
  $('#block').fadeTo('slow', 1);  
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜