【发布时间】:2017-11-23 13:39:45
【问题描述】:
我在页面上有复选框输入,并正在使用 ajax 过滤结果。
一个搜索选项是type,vendors 选项会根据所选的type 进行更新。但这意味着用于更新实际结果的更改功能不再适用于document.ready()。为了解决这个问题,我还调用了.ajaxComplete() 中的函数。
但由于在 ajaxComplete() 中调用了 ajax 调用,它会导致无限循环并使网站崩溃。
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
如何让 .change 函数在之前通过 ajax 调用输入复选框后仍然有效并且不会导致 .ajaxComplete() 循环?
任何帮助将不胜感激。 谢谢
【问题讨论】:
-
“但这意味着用于更新实际结果的更改函数在 document.ready() 中不再起作用” - 因为您将实际输入元素替换为我假设您的 AJAX 调用的结果?解决方案很简单,称为事件委托。
-
您需要将事件从主体委托给孩子。像这样: $( "body" ).delegate( "dynamicallyLoadedElement", "eventName", function() { //在这里做点什么 });
-
由于页面最初加载时您的元素不可用,因此未注册该事件。但是当你从 body 委托它时,事件最初是在 body 中注册的,然后在页面上可用时委托给元素
标签: javascript jquery ajax