jquery - 防止 jQuery 更改事件无限递归

标签 jquery onchange preventdefault

我在复选框上有一个 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/

相关文章:

javascript - 在 JavaScript 中哪里放置交互式对象?

javascript - 如何从 React 状态数组中删除未选中的复选框?

javascript - 如何使导航栏可点击

jQuery:仅在父链接上防止默认

jquery - 使用 jQuery 选择器选择一个元素,无论 ID 是什么

javascript - 函数 - 将元素 id 作为参数传递

javascript - 更改事件的复选框在 Safari 上不起作用

javascript - 从多个下拉菜单中获取值(value)(选择选项)

jquery - event.preventdefault 在 Firefox 中不起作用

具有多个值的 jQuery UI 自动完成 ajax