jquery - .load 之后调用函数(Jquery)

标签 jquery function load

在 .load 之后调用函数有点困难:

$(function(){
    $('a.pageFetcher').click(function(){
        $('#main').load($(this).attr('rel'));
    });
});

页面加载,但功能未触发:

$(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 ); 
    });
}
);
});

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

建议?

最佳答案

要在 .load() 完成后运行某些代码,您需要将代码放入 .load() 的完成函数中。加载操作是异步的,因此加载函数开始加载内容,然后立即返回,并且您的 JS 执行将继续(在加载完成之前)。因此,如果您尝试对新加载的内容进行操作,它还不会出现。

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

这就是为什么 .load() 采用完成函数作为参数。这是加载完成后将调用的函数。请参阅the relevant jQuery .load() doc了解更多信息。下面是带有补全函数的代码的样子。

$(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
    });
});

关于jquery - .load 之后调用函数(Jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9899066/

相关文章:

javascript - Jquery Slider UI 动态步长

javascript - 收到的 promise 待定

每次从函数返回时可以重置全局变量的值吗

javascript - 如何让 JQuery slider 一次加载一组元素

javascript - 使用 Bootstrap 模式作为成人内容警告的问题

java - 将模型对象从 Controller 返回到 Ajax jquery 在 Spring mvc 中不起作用

javascript - 如何将文本框弹出窗口(Jquery 工具提示或类似的)添加到 Canvas 中的 Fabric JS 图像?

javascript - 当未包装在匿名函数中时,属性的行为有所不同

Linux 操作系统/英特尔 64 位架构的 CPU 温度

javascript - 如何防止在 Javascript 代码执行之前出现 html 文本