see*_*613 4 javascript jquery events listener
我有容器和一些元素.他们有一些委派的事件监听器.
像这样
$('body').on('click', '.container .button', function() { ... });
Run Code Online (Sandbox Code Playgroud)
我想从容器中的所有元素中删除所有侦听器(无论事件类型和选择器).
像这样
$( "body" ).off("*", ".container *");
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
有人可以帮忙吗?感谢您的帮助.
更新的答案:
在评论中,你说过:
好.我有一个jsfiddle来解释这个问题.http://jsfiddle.net/KT42n/3我想从容器中的所有元素中删除所有处理程序
和
不幸的是在我的情况下使用命名空间是不可能的
哎哟.这将使它变得非常困难,尤其是因为一些委托处理程序可能与容器内部和外部的元素有关.
想到的唯一一件事就是要列出你想要阻止的所有事件名称(并不是那么多):
$(".container").on("click mousedown mouseup etc.", false);
Run Code Online (Sandbox Code Playgroud)
这将在事件到达之前停止事件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>
Run Code Online (Sandbox Code Playgroud)
原始答案:
您可以像这样删除所有处理程序body:
$("body").off();
Run Code Online (Sandbox Code Playgroud)
这包括委托的.
如果你想保留一些处理程序但不保留其他处理程序,我能想到的最简单的方法是在你挂起事件时命名事件,例如:
$("body").on("click.foo", "selector", ...);
Run Code Online (Sandbox Code Playgroud)
......等等.然后,您可以使用命名空间删除所有命名空间:
$("body").off(".foo", "selector");
Run Code Online (Sandbox Code Playgroud)
......甚至只是
$("body").off(".foo");
Run Code Online (Sandbox Code Playgroud)
...完全删除所有命名空间的,而不仅仅是那个选择器.
示例:实时复制
<!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>
Run Code Online (Sandbox Code Playgroud)