2012-02-01 71 views
0

我想取消绑定在包含当这个按钮被点击我使用这段代码 一个按钮一个div的事件,但它似乎没有工作,事件不断附加到按钮容器:jQuery的使用关()元素的最接近的容器上

$('body').on('click', '.button', function(){ 
     $('body').off('mouseleave',$(this).closest('.button-container')); 
}); 

我在做什么错了?

小提琴链接:http://jsfiddle.net/y3a6N/3/

感谢

+0

,什么是你的'在()'看起来像?什么是HTML的样子?你可以发布[JS小提琴演示](http://jsfiddle.net/)? – 2012-02-01 00:16:57

+0

我们必须看到您的HTML以了解如何提供帮助。 – jfriend00 2012-02-01 00:23:51

+0

更新小提琴链接:http://jsfiddle.net/y3a6N/3/ – Vincent 2012-02-01 00:40:21

回答

1

不能使用.on().off()的方式。你.on()代码是一个委托处理程序:

$('body').on('hover', '.button-container', function(){ 
    $(this).append('<p>New text</p>'); 
}); 

这是附着在身体对象,并寻求从类“按钮容器”的任何元素悬停事件的事件处理程序。

你不能再只是做.off()一个特定元素就像你想用这个做:

$('body').off('hover',$(this).closest('.button-container')); 

所以没有匹配的事件处理程序来删除不符合.on()签名。有了委托事件处理程序(就像你在这里使用.on()),它或者什么都不是。您要么删除整个事件处理程序。你不能告诉它仅仅代表一些对象停止委托。这里

function addText() { 
    $(this).append('<p>New text</p>'); 
} 

$('.button-container').on('hover', addText); 

$('.button').on('click', function(){ 
    $(this).closest('.button-container').off('hover', addText); 
}); 

工作的jsfiddle:

如果你的对象是不是动态的,因此你不需要委托事件处理,你可以做到这一点,除去要删除特定的事件处理程序http://jsfiddle.net/jfriend00/R2eQx/


,可能是简单的另一种方法是刚刚从像这样的对象删除类:

<div class="button-container active"> 
    <div class="button" style="border: 1px solid #cc0000">Roll over me to make text appear/Click me to stop making text appear (doesn't work)</div> 
</div> 

$('body').on('hover', '.active', function(){ 
    $(this).append('<p>New text</p>'); 
}); 

$('body').on('click', '.button', function(){ 
    $(this).closest(".button-container").removeClass("active"); 
}); 

和工作的jsfiddle这里:http://jsfiddle.net/jfriend00/byFpx/

这使得在地方事件处理程序,而只是将删除按钮的容器触发类,这样就不会在事件处理程序相匹配了。通过再次添加类,可以更容易地再次触发它。

+0

感谢您非常明确的答案 – Vincent 2012-02-01 00:53:50

+1

@Vincent - 我在回答结束,可能是更清洁添加另一种选择。它只是从父级添加/删除一个类。 – jfriend00 2012-02-01 01:04:08

+0

哇,你的回答真的超过我的期望,1000谢谢你,非常有帮助 – Vincent 2012-02-01 01:07:13

0

你关闭的用法是错误的。看你的旧代码和你的描述,我觉得这是你想达到什么目的:

var handler = function(){ 
     $(this).append('<p>New text</p>') } 
    $('body').on('hover', '.button-container', handler); 

    $('body').on('click', '.button', function(){ 

     $('body').off('hover', ".button-container", handler); 
    }); 

这将禁用您指定的悬停事件处理程序使用第一.on()