多个加载事件共享同一个监视器

时间:2012-07-16 02:17:48

标签: jquery jquery-load

我想创建一个使用HTML5的CMS,当索引执行时,它会加载标题,容器和页脚。我使用以下代码来执行此操作

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

但是,我想将一些事件处理程序绑定到任何标题,容器或页脚,当然,像$('a')一样的处理程序。单击(...)为每个标记标题,容器和页脚。当然,我可以为每个加载器绑定三个成功函数,但我认为这不是一个好方法。有没有办法检查每个加载事件是否已完成?

1 个答案:

答案 0 :(得分:0)

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

分散到容器

这是迄今为止最简单的方法。容器中的任何现有或未来<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()动作的失败都不会影响其他动作。

。当(许诺).done()

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

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()操作失败都将完全禁止点击处理程序的附件。

相关问题