2016-07-06 42 views
2

我想问,如何从document中删除事件处理程序,但只有那些具有命名空间的事件处理程序?解除与命名空间的一些事件处理程序

我有这段代码,我没有看到任何错误,但这个函数总是触发mouseuptouchend的事件处理程序,即使在.unbind之后。我确信我在这段代码中有一些错误。

$(".inp").on("autocompleteresponse", function(event, ui) { 
    $(document).bind("mouseup.test, touchend.test", function(e) { 
     var container = $('.ui-autocomplete'); 
     if (!container.is(e.target) && container.has(e.target).length === 0) { 
      if (ui.content.length > 0) { 
       ui.item = ui.content[0]; 
       console.log (ui.item); 
       $(".inp").val(ui.item.label); 
       // This will fire always, on document click, should only once per time 
       $(document).unbind("mouseup.test, touchend.test"); 
      } 
     } 
    }); 
}); 

感谢意见

回答

2

首先,on()off()现在的首选方法,而不是过时的bind()unbind()

其次,要解决您的问题,您应该用空格而不是逗号分隔事件。试试这个:

$(".inp").on("autocompleteresponse", function(event, ui) { 
    $(document).on("mouseup.test touchend.test", function(e) { 
     var container = $('.ui-autocomplete'); 
     if (!container.is(e.target) && container.has(e.target).length === 0) { 
      if (ui.content.length > 0) { 
       ui.item = ui.content[0]; 
       console.log(ui.item); 
       $(".inp").val(ui.item.label); 

       $(document).off("mouseup.test touchend.test"); 
      } 
     } 
    }); 
}); 

还要注意的是,如果你想关闭与命名空间相关联的所有事件,你可以通过单独的命名空间的off()方法:

$(document).off(".test")