2

我通过 $(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 事件处理程序也解除绑定,这对我来说是个问题。

4

2 回答 2

1

它称为事件冒泡。嵌套元素的事件向上传递给父级。

您应该从该处理程序bind返回#mid并返回false

于 2011-03-16T00:27:49.470 回答
0

只有一个事件绑定到文档。由于冒泡,事件将向上发送到 DOM 层次结构,直到它的传播停止,或者它到达文档。

如果它来自#mid,您可以修改回调以忽略此事件,或者使用内置的委托/直播来实现相同的效果。

$(document).delegate('[id!="mid"]', 'click.custom', fun);

这将忽略来自 id 为“mid”的元素的事件。另一种选择是修改函数本身。

function fun() {
    if (this.id == "mid") { 
        return; // if event came from #mid, ignore it.
    }
    // continue processing as normal
}
于 2011-03-16T00:41:15.813 回答