最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery.off() is not removing binding - Stack Overflow

programmeradmin0浏览0评论

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?

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
        });
      });
    })();
  }
});

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?

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
        });
      });
    })();
  }
});
Share Improve this question asked Jan 15, 2012 at 7:55 StevenSteven 1,1171 gold badge8 silver badges21 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

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, this is the '.renewal-warning' element that was clicked, not the #signRentalContainer element.


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.

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

Because the this refer to the context of the handle function, not the function itself.

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

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

BTW, any reason we can't use unbind directly here?

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

发布评论

评论列表(0)

  1. 暂无评论