更新答案:
在 cmets 中,你说过:
好的。我有一个 jsfiddle 来解释这个问题。 http://jsfiddle.net/KT42n/3我想从容器中的所有元素中删除所有处理程序
和
不幸的是,在我的情况下使用命名空间是不可能的
哎哟。这将使其变得非常困难,尤其是因为一些委托处理程序可能与容器内外的元素相关。
想到的唯一一件事是列出您想要阻止的所有事件名称(没有那么多):
$(".container").on("click mousedown mouseup etc.", false);
这将在事件到达 body 之前停止事件,因此在委托处理程序看到它之前:Live Example
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Stop Delegated Handlers Within Container</title>
</head>
<body>
<p>Outside the container</p>
<div class="container">
<p>Inside the container</p>
</div>
<script>
(function() {
// Other handlers
$("body").on("click", "p", function() {
display("paragraph clicked");
});
// Prevent clicks within container
$(".container").on("click mousedown etc", false);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
原答案:
您可以像这样从 body 中删除 所有 处理程序:
$("body").off();
这包括委托的。
如果您想保留一些处理程序而不保留其他处理程序,我能想到的最简单的方法是在连接事件时为其命名,例如:
$("body").on("click.foo", "selector", ...);
...等等。然后你可以使用命名空间来删除它们:
$("body").off(".foo", "selector");
...甚至只是
$("body").off(".foo");
...完全删除所有命名空间,而不仅仅是该选择器的那些。
例如:Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Removing All Delegated Handlers</title>
</head>
<body>
<div class="clickable">Click me</div>
<div class="mousemoveable">Mouse over me</div>
<input type="button" id="theButton" value="Remove handlers">
<script>
(function() {
$("body").on("click.foo", ".clickable", function() {
display("click");
});
$("body").on("mousemove.foo", ".mousemoveable", function() {
display("mousemove");
});
$("#theButton").click(function() {
$("body").off(".foo");
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>