我在复选框上有一个 jQuery 更改事件,该事件进行 Ajax 调用,然后突出显示该复选框所属的表行。当 Ajax 调用报告错误时,我遇到了问题 - 在这种情况下,我想反转复选框单击(我正在使用 that.prop("checked", !that.prop("checked"))
这样做)。然而,发生的情况是它进入了调用更改事件的无限循环。正如您所看到的,为了阻止这种行为,我尝试设置一个名为 ajaxInProgress 的变量,但它似乎没有像我希望的那样工作。任何人都可以提供替代方法或发现错误吗?我不确定重置复选框的方式是否必要 - 是否可以重置复选框并仍然阻止更改事件启动?
var ajaxInProgress = false; //add this to stop recursive calls when errors occur
jQuery(document).ready(function() {
jQuery(".cc").change(function (e) {
if (ajaxInProgress) return;
var mode = "remove"
if (jQuery(this).attr("checked")) {
mode = "add"
}
//grab the application ID from the checkbox ID
var thisApp = this.id.substr(3);
var that = jQuery(this);
ajaxInProgress = true;
jQuery.get("/particular/edit-ajax", { application_id: thisApp,
party_id: 1920,
party_rel_id: 21,
mode: mode} , function(response) {
if (response == 0) {
that.closest('tr').removeClass('even').removeClass('odd').addClass('highlight');//highlight the tr
} else {
e.preventDefault();
that.prop("checked", !that.prop("checked")); //reset the checkbox if there was an error
alert("Please contact support - couldn't update database for application "+thisApp+". Response was: "+response);
}
});
ajaxInProgress = false;
});
});
最佳答案
这一切看起来都很复杂,而且我会这样做:
(function($) {
$(function() {
function sendAjax(e) {
var data = {
application_id: this.id.substr(3),
party_id: 1920,
party_rel_id: 21,
mode: this.checked?'add':'remove',
},
that=this;
$.ajax({
type: 'GET',
data: data
}).done(function() {
$(that).closest('tr').removeClass('even odd').addClass('highlight');
}).fail(function(response) {
e.preventDefault();
that.checked = !that.checked;
alert("Please contact support - couldn't update database for application "+that.id.substr(3)+". Response was: "+response);
}).always(function() {
$(".cc").one('change', sendAjax);
});
}
$(".cc").one('change', sendAjax);
});
})(jQuery);
关于jquery - 防止 jQuery 更改事件无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899978/