如何在ajaxed内容上使用包装函数的jquery .delegate()?

时间:2010-12-14 23:23:18

标签: jquery ajax

假设您有一个名为/start.html的页面, 在那个页面中你有一个包装函数 在身体加载时被调用。

function eatApples() {  
 // some code  
}  
function eatOranges() {  
// some code  
}  
function eatFruit() {  
$(eatApples());
$(eatOranges()); 
}  
// call the eatFruit function on page load
$(eatFruit()); 

现在假设您还有一个名为/end.html的页面, 此页面包含ajaxed内容。此外, 你想在那个ajaxed内容上调用eatFruit()。

这可以通过jQuery的委托实时功能实现吗? http://api.jquery.com/delegate/

1 个答案:

答案 0 :(得分:2)

首先,你的代码应该是

function eatApples() {  
 // some code  
}  
function eatOranges() {  
// some code  
}  
function eatFruit() {  
  eatApples();
  eatOranges(); 
}  
// call the eatFruit function on page load
$(eatFruit);

除非eatAppleseatOranges返回功能。

现在,如果使用ajax调用end.html,则jquery允许在加载ajax内容时执行回调处理程序。

委托和实时功能用于控制用户交互发生的事件。

如果新内容符合使用委托或实时方法时指定的条件,那么是的,它将适用于加载了ajax的内容。

例如,如果您设置了

$('.aclass').live('click',function(){
   alert('clicked');
});

然后,如果从ajax加载的内容具有类aclass的元素,它也会在单击时触发警报。

如果您能提供更多信息,您将获得更详细的答案。