javascript - 覆盖 JQuery 之前的回调函数

标签 javascript jquery callback

我在回调函数方面遇到了这个问题。我有这个功能来显示警报消息,并且它有一个回调 (okcallback) 如果提供的话将被执行:

function ErrorAlert(msg,okcallback) {

    ISAPP.ui.loader_modal_header.html('<h4 class="modal-title">'+ label.alertLabel +'</h4>');
    ISAPP.ui.loader_modal_body.html(msg);
    ISAPP.ui.loader_modal_footer.html('<div class="clearfix ">' +
              '<a id="modal-alert-close" class="btn green pull-right">' +
                '<label>'+ label.acceptLabel +'</label>' +
                ' <i class="fa fa-check-circle"></i>' +
              '</a>' + 
            '</div>');
    ISAPP.ui.loader_modal_header.show();
    ISAPP.ui.loader_modal_body.show();
    ISAPP.ui.loader_modal_footer.show();
    ISAPP.ui.loader_modal.modal('show');

    $(document).on('click','#modal-alert-close',
            function(){
                ISAPP.ui.loader_modal_footer.html('');
                ISAPP.ui.loader_modal.modal('hide');
                if(okcallback){
                    okcallback();
                }
            }
    );      
}

当我在第一次执行函数时将它与回调一起使用或没有回调时,它工作正常。但是当它第二次执行时,即使第二次执行没有回调函数,上一次执行的任何回调都会延续到第二次执行。

示例:
第一次执行(关闭消息后会变成空白)

ErrorAlert("Pincode has been sent to " + email,
            function(){
                location.href = "#/blank";  
            }
    );

第二次执行(关闭消息后不应该做任何事情)

ErrorAlert("Username is mandatory");

但实际情况是,该函数仍然转到“#/blank”,这意味着它运行之前的回调函数。为什么会这样?我该如何防止这种情况发生?

谢谢。

最佳答案

我假设您的页面中没有多次相同的 ID,即您的第一个对话框在您打开新对话框之前关闭。

您可以使用 off 取消绑定(bind),但没有理由在这里使用委托(delegate)。一个简单的解决方案是绑定(bind)到新添加的元素而不是整个文档。这样,绑定(bind)将与元素一起删除。

替换

$(document).on('click','#modal-alert-close'

$('#modal-alert-close').on('click',

关于javascript - 覆盖 JQuery 之前的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010083/

相关文章:

android - 如何使用 Volley 库和 NetworkImageView 在 setImageUrl 上完成回调?

ruby-on-rails - View 渲染后 Rails 中的回调(用于记录目的)

c++ - 从 C++ 调用 Cython 函数

javascript - 两个参数的 Javascript 函数

c# - JQuery DataTable 中复选框的 Javascript 验证

javascript - jquery水平滚动条消失

javascript - 具有更多图像的 Jquery 1 id 并更改所有图像宽度/高度/位置

javascript - 无法更改变量值javascript

javascript - 遍历 $element 的子元素

javascript - 原型(prototype)继承javascript