javascript jQuery.off() 不会删除绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8868293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:50:03  来源:igfitidea点击:

jQuery.off() is not removing binding

javascriptjquery

提问by Steven

For some reason jQuery.off('click') doesn't seem to be working here. When the 'Yes' button is clicked in the model another model just pops up. What am I doing wrong?

出于某种原因 jQuery.off('click') 似乎在这里不起作用。当单击模型中的“是”按钮时,会弹出另一个模型。我究竟做错了什么?

code:

代码:

$(function(){

  //If there are warnings on the page bind alert
  if ($('.renewal-warning').length > 0){

    (function (){

      $('#signRentalContainer').on('click', '.renewal-warning', function(e){

        var buttonHandle = this;

        //Prevent submission
        e.preventDefault();

        //Show warning model
        $.modal({
          content: $('#renewalWarning').html(),
          title: "Order Renewal Warning",
          buttons: {
            'Yes': function(win) { $(buttonHandle).off('click').click(); },
            'No': function(win) { win.closeModal(); }
          },
          maxWidth: 250,
          closeButton: false
        });
      });
    })();
  }
});

回答by

Pretty sure you're going to need to provide it the same element, as well as the same selector.

非常确定您将需要为其提供相同的元素以及相同的选择器。

$('#signRentalContainer').off('click', '.renewal-warning');

In the .on()handler, thisis the '.renewal-warning'element that was clicked, not the #signRentalContainerelement.

.on()处理程序中,this'.renewal-warning'被点击的元素,而不是#signRentalContainer元素。



If there are several of these '.renewal-warning'elements, and you only want to disable one at a time, the simplest way is to change its class so that it no longer matches the selector.

如果有多个这样的'.renewal-warning'元素,而您只想一次禁用一个,最简单的方法是更改​​其类,使其不再与选择器匹配。

$(this).removeClass('renewal-warning')
       .addClass('renewal-warning-disabled');

回答by satoru

Because the thisrefer to the context of the handle function, not the function itself.

因为this引用的是句柄函数的上下文,而不是函数本身。

Try making it a named function, then refer to it when you call off:

尝试将其设为命名函数,然后在调用时引用它off

$("body").off("click", '#signRentalContainer', buttonHandle);

$("body").off("click", '#signRentalContainer', buttonHandle);

BTW, any reason we can't use unbinddirectly here?

顺便说一句,我们不能unbind在这里直接使用的任何原因?

$("#signRentalContainer").unbind("click");

$("#signRentalContainer").unbind("click");