如何从元素中分离jquery事件(函数)

Ale*_*lex 3 javascript jquery events

如果我的ajax请求成功,我想删除此click事件:

  $('.el a').live('click', function(event){
    event.preventDefault();

    $.ajax({
      url: $(this).attr('href'),
      type: 'GET',      
      success: function(response){

         // how to detach this function here? (the live click event)
      }
    });
  });
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 6

您的问题是live没有绑定到任何特定的元素集,它绑定到click事件发生时匹配特定选择器的任何元素.这意味着你不能使用unbindoff停止点击触发处理程序.

但是,您可以稍微修改选择器以排除具有特定类的元素,然后添加该类以告知live忽略您的元素:

$('.el a:not(.been-clicked)').live('click', function(event){
  event.preventDefault();

  var $this = $(this);
  $.ajax({
    url: $this.attr('href'),
    type: 'GET',      
    success: function(response){
      $this.addClass('been-clicked');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

演示技术:http://jsfiddle.net/ambiguous/Deh5j/


Greg Pettit在评论中是正确的,live如果你正在使用jQuery 1.7而不应该再使用它,即使在1.6中也有点不赞成.你通常最好delegate在1.7之前使用,on如果你使用1.7:

$(document).on('click', '.el a:not(.been-clicked)', function() {
  //...
});
Run Code Online (Sandbox Code Playgroud)

您仍然无法使用unbindoff停止此版本on(除非在非常狭窄的情况下,例如,如果您只有一个匹配的元素,.el a并且您只附加了一个单击处理程序(或者如果您使用命名函数)).如果你使用"实时"样式绑定,你仍然需要类似上面的"添加类作为标志"技巧,如果你绑定到绑定点击处理程序时存在的一组特定元素,那么你应该' T为使用live在所有的,你应该使用的一个bind,clickon一个处理程序只是那些特定元素绑定; 然后你可以使用unbindoff分离处理程序.或者更好,你只是使用one并让jQuery担心分离处理程序.