Jquery 多个加载事件共享同一个监视器
我想用HTML5创建一个CMS,当索引执行时,它会加载页眉、容器和页脚。我使用以下代码来实现这一点Jquery 多个加载事件共享同一个监视器,jquery,jquery-load,Jquery,Jquery Load,我想用HTML5创建一个CMS,当索引执行时,它会加载页眉、容器和页脚。我使用以下代码来实现这一点 $('#header').load("header.html"); $('#container').load("container.html"); $('#footer').load("footer.html)"); 它可以工作,但是,我想将一些事件处理程序绑定到头、容器或页脚中,当然是相同的处理程序,如$('a')。在头、容器和页脚中为每个标记单击(…)。当然,我可以为每个加载程序绑定三个成功
$('#header').load("header.html");
$('#container').load("container.html");
$('#footer').load("footer.html)");
它可以工作,但是,我想将一些事件处理程序绑定到头、容器或页脚中,当然是相同的处理程序,如$('a')。在头、容器和页脚中为每个标记单击(…)。当然,我可以为每个加载程序绑定三个成功函数,但我认为这不是一个好方法。是否有办法检查是否每个加载事件都已完成?有多种方法可以实现这一点: 对集装箱的拆离 这是迄今为止最简单的方法。容器中任何现有或将来的
标记都将获得指定的单击处理程序的功能
$(function(){
$('#header, #container, #footer').on('click', 'a', function() {
//...
});
$('#header').load("header.html");
$('#container').load("container.html");
$('#footer').load("footer.html");
});
任何.load()
操作的失败都不会影响其他操作
命名函数
使用这种方法,相同的命名函数被指定为所有三个.load()
调用的“complete”回调
$(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()
操作的失败都不会影响其他操作
.何时(承诺)完成
在这种方法中,.load()
被替换为$.ajax
,它返回一个非常方便的“jqXHR”(promise)对象.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()
操作的失败都将完全禁止click处理程序的连接。下载-为什么没有注释?要有坚定信念的勇气。如果有什么我能学的,那就让我学吧。
$(function(){
$('#header, #container, #footer').on('click', 'a', function() {
//...
});
$('#header').load("header.html");
$('#container').load("container.html");
$('#footer').load("footer.html");
});