.load之后调用函数(Jquery)

Mat*_*att 12 jquery load function

在.load之后获取函数时遇到一些困难:

$(function(){
    $('a.pageFetcher').click(function(){
        $('#main').load($(this).attr('rel'));
    });
});
Run Code Online (Sandbox Code Playgroud)

页面加载,但函数不会触发:

$(function(){
    var $container = $('#container');
    $container.imagesLoaded(function(){
        $container.masonry({
            itemSelector: '.box',
    });
});
$container.infinitescroll({
    navSelector  : '#page-nav',
    nextSelector : '#page-nav a',
    itemSelector : '.box',
    loading: {
        finishedMsg: 'Nothing else to load.',
        img: 'http://i.imgur.com/6RMhx.gif'
    }
},
function( newElements ) {
    $.superbox.settings = {
        closeTxt: "Close this",
        loadTxt: "Loading your selection",
        nextTxt: "Next item",
        prevTxt: "Previous item"
    };
    $.superbox();
    var $newElems = $( newElements ).css({ opacity: 0 });
    $newElems.imagesLoaded(function(){
        $newElems.animate({ opacity: 1 });
        $container.masonry( 'appended', $newElems, true ); 
    });
}
);
});
Run Code Online (Sandbox Code Playgroud)

我试图将它们组合起来,以便在.load之后调用第二个函数(在对此站点进行一些搜索并查看给定的答案/示例之后),但似乎没有任何工作正常.

建议?

jfr*_*d00 30

要在.load()完成后运行一些代码,您需要将代码放在完成函数中.load().加载操作是异步的,因此加载函数开始加载内容,然后立即返回并继续执行JS(在加载完成之前).所以,如果你试图对新加载的内容进行操作,它就不会存在.

在您的代码现在编写时,您有两个代码块,它们都在原始HTML文档准备就绪时运行.第一个块开始.load()操作.第二个操作预计.load()已经完成,但尚未完成,因此.load()操作中的内容尚不可用.

这就是为什么.load()将完成函数作为参数.这是一个在负载完成时调用的函数.有关.load()更多信息,请参阅相关的jQuery 文档.以下是使用完成函数时代码的外观.

$(function(){
    $('a.pageFetcher').click(function(){
        $('#main').load($(this).attr('rel'), function() {
            // put the code here that you want to run when the .load() 
            // has completed and the content is available
            // Or, you can call a function from here
        });
        // the .load() operation has not completed here yet
        // it has just been started
    });
});
Run Code Online (Sandbox Code Playgroud)