【问题标题】:can't unbind a element with jquery无法使用 jquery 取消绑定元素
【发布时间】:2013-12-12 06:31:25
【问题描述】:

我正在开发一个创建此 jquery 事件的项目:

$('input.checkout-continue:not(.checkout-processed)', context).addClass('checkout-processed').click(function() {
      var $this = $(this);
      $this.clone().insertAfter(this).attr('disabled', true).next().removeClass('element-invisible');
      $this.hide();
    });

这可以防止用户单击提交按钮两次。 我写了一个提交事件,我需要暂时取消绑定该事件并在完成后将其重新打开。 (我需要这样做,否则,在我单击提交后,按钮会冻结并且没有响应。)我尝试从这个开始:

$('input.checkout-continue:not(.checkout-processed)').unbind("click");
        $('#commerce-checkout-form-checkout').submit(function() {
          if($('#donation-amount-selection-form .form-item-donation-amount').val() == "" &&
             $('#donation-amount-selection-form .form-item-donation-custom-amount').val() == "") {
            var message = "请输入捐款金额"
            $('#donation-amount-selection-form').prepend(message);
            event.preventDefault();
          }

但它没有解除绑定,提交按钮保持冻结状态。

【问题讨论】:

    标签: jquery bind


    【解决方案1】:

    该事件没有解除绑定,因为选择器:'input.checkout-continue:not(.checkout-processed) 仅用于选择没有 .checkout-processed CSS 类的元素。该类是在开头添加的:

    $('input.checkout-continue:not(.checkout-processed)', context).addClass('checkout-processed');
    

    为了解除对input.checkout-continue的点击,最好缓存jQuery对象,以便以后可以引用它而无需重新查询DOM。

    // Caches the selector since we'll use it to bind and unbind.
    var $input = $('input.checkout-continue:not(.checkout-processed)');
    
    var onClick = function () {
    
      // Caches the clicked element.
      var $this = $(this);
    
      $this.attr('disabled', true);
    
      // After some time, re-enable the button but unbind the click event.
      window.setTimeout(function () {
        $this.attr('disabled', false);
        $input.unbind('click', onClick);
      }, 3000);
    
    };
    
    $input.bind('click', onClick);
    

    Live Demo

    在本例中,我们只需将disabled 属性设置为开/关即可切换输入的状态(无需克隆和隐藏)。

    【讨论】:

    • 我不明白你的代码。首先,当您说这是错误的选择器时,您是否无意中在实际代码中添加了 not(.checkout-processed) ?二、jquery submit 事件在哪里?我只看到 onClick 变量。因此,我不明白 $this 指的是什么。
    • 我刚试过 $('input.checkout-continue').unbind("click");看看它是否会取消绑定事件,但它不会
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多