如何处理Ajax内容中的Fancybox?

我使用ajax在我的网站上展示内容。单击菜单时,它将在#content div中打开内容。

这是我的ajax代码:

$(document).ready(function() {
    $('.menu li a').click(function(){
        var toLoad = $(this).attr('href')+' #content';
        $('#content').animate({"width": "0px"},'normal',loadContent);
        window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
        function loadContent() {
            $('#content').load(toLoad,'',showNewContent());
        }
        function showNewContent() {
            $('#content').animate({"width": "0px"},'fast');
            $('#content').animate({"width": "664px"},'fast');
        }
        return false;
    });
});

我想在Ajax内容中使用Fancybox灯箱效果(http://fancybox.net), 以下是Fancybox所需的代码:

    <script type="text/javascript" src="js/fancybox-1.3.4.pack.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("a#example4").fancybox({
                'opacity'       : true,
                'overlayShow'   : false,
                'transitionIn'  : 'elastic',
                'transitionOut' : 'elastic',
            });
        });
    </script> 

如何使它正常工作? Ajax调用?

First this line is wrong

$('#content').load(toLoad,'',showNewContent());

It is saying call showNewContent() and assign whatever it returns to this event.

It should be

$('#content').load(toLoad,'',showNewContent);

Now it says to assign a reference to this function and run it when it is needed.

Now to answer your question, you need to call $("a#example4").fancybox({...}); after the content is loaded, so that means you would put it in the function showNewContent.

In the load callback handler should be a function pointer showNewContent() will right away call the function. Try this.

$(document).ready(function() {
    $('.menu li a').click(function(){
        var toLoad = $(this).attr('href')+' #content';
        $('#content').animate({"width": "0px"},'normal',loadContent);
        window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
        function loadContent() {
            $('#content').load(toLoad,'',showNewContent);
        }
        function showNewContent() {
            $("#example4").fancybox({
                'opacity'       : true,
                'overlayShow'   : false,
                'transitionIn'  : 'elastic',
                'transitionOut' : 'elastic',
            });
        }
        return false;
    });
});