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

javascript - jquery off not working - Stack Overflow

programmeradmin2浏览0评论

I can't unbind event use off.

I was trying to bind click event, then bind mouseleave event and callback unbind click, but not working.
el is dom create and append by script that's why I use document.on... el

so I tried below include mented code for test not working too.... do I miss understand something?

jquery-1.11.1.min.js

/

var el = $('div')
$(document).on('click', el, function() {
  console.log('oncli')
});
//$(document).on('mouseleave', el, function() {
  //$(document).off('click', el, function() {
    //console.log('offcli')
  //});
  //$(document).off('click', el);
  el.off('click');
//});

I can't unbind event use off.

I was trying to bind click event, then bind mouseleave event and callback unbind click, but not working.
el is dom create and append by script that's why I use document.on... el

so I tried below include mented code for test not working too.... do I miss understand something?

jquery-1.11.1.min.js

https://jsfiddle/70t6jtns/

var el = $('div')
$(document).on('click', el, function() {
  console.log('oncli')
});
//$(document).on('mouseleave', el, function() {
  //$(document).off('click', el, function() {
    //console.log('offcli')
  //});
  //$(document).off('click', el);
  el.off('click');
//});
Share Improve this question edited Dec 10, 2016 at 8:35 user1775888 asked Dec 10, 2016 at 8:30 user1775888user1775888 3,31314 gold badges49 silver badges67 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 8

First, on doesn't accept jQuery objects as the second argument, so $(document).on('click', el, function() {... doesn't make sense.

The main issue is that you're using event delegation in one case but expecting a directly-attached handler in the other case. You're attaching your click handler to document, but then trying to detach it from a specific element (el). You have to remove it from the same thing you attached it to.

If you want to attach the handler to el and detach it later, use el consistently as the target:

el.on("click", function() { ...

then

el.off("click");

If the handler has to be delegated, you'll want to be sure, again, that you're removing the same thing you're adding. So for instance,

$(document).on("click", "selector-for-the-element", function() { ...

then

$(document).off("click", "selector-for-the-element");

I was facing the same issue. Because i added the on listener on document and trying off with element. that was the issue in my case.

发布评论

评论列表(0)

  1. 暂无评论