【问题标题】:Multiple load event share a same monitor多个加载事件共享同一个监视器
【发布时间】:2012-07-16 02:17:48
【问题描述】:

我想创建一个使用 HTML5 的 CMS,当索引执行时,它会加载页眉、容器和页脚。我使用以下代码来做到这一点

$('#header').load("header.html");
$('#container').load("container.html");
$('#footer').load("footer.html)");

它可以工作,但是,我想将一些事件处理程序绑定到任何页眉、容器或页脚中,当然,对于每个 a 标签,与 $('a').click(...) 相同的处理程序页眉、容器和页脚。而且我当然可以为每个loader绑定三个成功函数,但我认为这不是一个好办法。有没有办法检查每个加载事件是否完成?

【问题讨论】:

    标签: jquery jquery-load


    【解决方案1】:

    有很多方法可以解决这个问题:

    对容器的委托

    这是迄今为止最简单的方法。容器中任何现有或未来的<a> 标记都将获得指定点击处理程序的功能。

    $(function(){
        $('#header, #container, #footer').on('click', 'a', function() {
            //...
        });
    
        $('#header').load("header.html");
        $('#container').load("container.html");
        $('#footer').load("footer.html");
    });
    

    任何.load() 操作的失败都不会影响其他操作。

    命名函数

    使用这种方法,同名函数被指定为所有三个.load() 调用的“完成”回调。

    $(function() {
        function bindHandler() {
            $(this).find("a").on('click', function() {
                //...
            });
        }
    
        $('#header').load("header.html", bindHandler);
        $('#container').load("container.html", bindHandler);
        $('#footer').load("footer.html", bindHandler);
    });
    

    同样,任何.load() 操作的失败都不会影响其他操作。

    .when(promises).done()

    在这种方法中,.load() 被替换为 $.ajax,它返回一个非常方便的“jqXHR”(承诺)对象。 .load() 不能以这种方式使用,因为它返回一个标准的 jQuery 对象;它的 promise 对象是不可访问的。

    function load(url, selector) {
        //make ajax request and return jqXHR (promise) object
        return $.ajax(url, {
            success: function(data){
                $(selector).html(data);
            }
        });
    }
    
    $.when(
        load("header.html", '#header'),
        load("container.html", '#container'),
        load("footer.html)", '#footer')
    ).done(function() {
        // All three ajax requests have successfully completed
        $("#header, #container, #footer").find("a").on('click', function() {
            //...
        });
    });
    

    只有在所有三个加载操作都成功时,才应使用最后一种方法。任何.load() 操作的失败都将完全禁止点击处理程序的附加。

    【讨论】:

    • 拒绝投票者 - 为什么没有 cmets?有你的信念的勇气。如果有什么我能学的,那就让我学吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 2010-09-18
    • 1970-01-01
    相关资源
    最近更新 更多