所以想象一下这个场景,我有一个列表,它有一些分页,当用户单击下一步时,链接被 jQuery 劫持,它使用 $.ajax
函数(我在下面提供了)去获取下一页内容并将它们显示在原始容器中。这包括分页链接,我们也希望它们更新。
第一个页面更改工作正常,但在这个阶段我们已经失去了链接元素和 jQuery 规则之间的绑定(bind):
$('#paging a').click(function(event) {
event.preventDefault();
getElementContents('#target_container','',$(this).attr('href'),false);
// arguements are (target element, data (for $ajax), url (for $ajax), highlight)
});
我必须采取哪些选项来维护事件和函数之间的绑定(bind)?
作为引用,这是我的 $.ajax
的包装函数:
var ajax_count = 0;
function getElementContents(target,data,url,highlight) {
if(url==null) {
url='/';
}
if(data==null) {
var data=new Array();
}
if(highlight==null || highlight==true) {
highlight=true;
} else {
highlight=false;
}
$.ajax({
url: url,
data: data,
beforeSend: function() {
/* if this is the first ajax call, block the screen */
if(++ajax_count==1) {
$.blockUI({message:'Loading data, please wait'});
}
},
success: function(responseText) {
/* we want to perform different methods of assignment depending on the element type */
if($(target).is("input")) {
$(target).val(responseText);
} else {
$(target).html(responseText);
}
/* fire change, fire highlight effect... only id highlight==true */
if(highlight==true) {
$(target).trigger("change").effect("highlight",{},2000)
}
},
complete: function () {
/* if all ajax requests have completed, unblock screen */
if(--ajax_count==0) {
$.unblockUI();
}
},
cache: false,
dataType: "html"
});
}
谢谢! :-)
编辑
嗯,刚刚找到this question ...正在研究它:-)
最佳答案
尝试使用jquery.live:
$('#paging a').live('click', function(event) {
event.preventDefault();
getElementContents('#target_container','',$(this).attr('href'),false);
// arguements are (target element, data (for $ajax), url (for $ajax), highlight)
});
如果使用 jQuery 1.9 或更高版本,.live 不再存在,因此您可以使用 .on 函数代替:
$(document).on('click', '#paging a', function (event) {
event.preventDefault();
getElementContents('#target_container','',$(this).attr('href'),false);
});
关于jQuery、AJAX 内容失去绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2773573/