无法取消绑定到 $(document) 的事件
我通过 $(document).bind() 将事件处理程序绑定到页面的每个元素。
有谁知道如何解除特定元素的此处理程序的绑定?
这是我的示例代码,它不能按我想要的方式工作:
<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"> </script>
</head>
<body>
<div id="mid" style="cursor:pointer" >click me</div>
<div>sample</div>
<script type="text/javascript">
var fun = function() {
alert('default handler');
};
$(document).bind('click.custom', fun);
//trying to unbind the handler but it remains there
$("#mid").unbind('click.custom');
</script>
</body>
</html>
考虑到丹尼尔的回答,这里又出现了这个问题:
var ff = function() {
alert('additional');
}
$(document).bind('click.custom', fun);
$(document).bind('click.custom2', ff);
$("#mid").bind('click.custom', false);
这里 fun 事件处理程序与 #mid 元素完全解除绑定,但 ff 事件处理程序也未绑定,这对我来说是一个问题。
I have event handler bound to every element of the page via $(document).bind().
Does anybody know how to unbind this handler for particular element?
Here is my sample code that doesn't work the way I want:
<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"> </script>
</head>
<body>
<div id="mid" style="cursor:pointer" >click me</div>
<div>sample</div>
<script type="text/javascript">
var fun = function() {
alert('default handler');
};
$(document).bind('click.custom', fun);
//trying to unbind the handler but it remains there
$("#mid").unbind('click.custom');
</script>
</body>
</html>
Considering Daniel's answer here is this problem again:
var ff = function() {
alert('additional');
}
$(document).bind('click.custom', fun);
$(document).bind('click.custom2', ff);
$("#mid").bind('click.custom', false);
here fun event handler was perfectly unbound from #mid element, but ff event handler was unbound also and that is a problem for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这称为事件冒泡。嵌套元素的事件将传递给父元素。
您应该
绑定
到#mid
并从该处理程序返回false
。Its called event bubbling. The events of the nested elements go up to the parents.
You should
bind
to#mid
and returnfalse
from that handler.只有一个事件绑定到文档。由于冒泡,事件将沿 DOM 层次结构向上发送,直到其传播停止或到达文档。
您可以修改回调以忽略来自
#mid
的事件,或者使用内置的 delegate/live 来实现相同的效果。这将忽略来自 id 为“mid”的元素的事件。另一种替代方法是修改函数本身。
There is only a single event bound to the document. Because of bubbling, the event will be sent up the DOM hierarchy until its propagation is stopped, or it reaches the document.
You could either modify the callback to ignore this event if it came from
#mid
, or use the in-built delegate/live to achieve the same effect.This will ignore events coming from an element having the id "mid". Another alternate is to modify the function itself.