2016-07-06 2 views
2

私に質問したいのは、documentからイベントハンドラを削除するにはどうすればよいのですか?名前空間でいくつかのイベントハンドラをアンバインド

私はこのコードを持っていますが、エラーはありませんが、.unbindの後でも、このハンドラは常にmouseuptouchendのイベントハンドラを起動します。私はこのコードでいくつかの誤りがあると確信しています。アドバイスまず

答えて

2

ため

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

おかげで、on()off()は今、代わりに時代遅れbind()unbind()の好ましい方法です。

第2に、問題を解決するには、イベントをカンマではなくスペースで区切る必要があります。これを試してみてください:

$(".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") 
関連する問題