这应该适用于您想要做的事情:http: //jsfiddle.net/7jQJj/3/
var elesBound = []
var func = function () {
console.log("func from ele: "+this.tagName+"(id: "+this.id+")");
}
var associateListener = function (event) {
console.log("associateListener");
var element = event.srcElement || event.target;
element.addEventListener("click", func, false);
element.addEventListener("mousedown", func, false);
element.addEventListener("mouseup", func, false);
elesBound.push(element);
};
var addListeners = function (win) {
console.log("addListeners");
win.document.addEventListener("click", associateListener, true);
win.document.addEventListener("mousedown", associateListener, true);
win.document.addEventListener("mouseup", associateListener, true);
};
var deleteListeners = function (win) {
console.log("deleteListeners");
win.document.removeEventListener("click", associateListener, true);
win.document.removeEventListener("mousedown", associateListener, true);
win.document.removeEventListener("mouseup", associateListener, true);
for (var i = 0; i < elesBound.length; i++) {
elesBound[i].removeEventListener("click", func, false);
elesBound[i].removeEventListener("mousedown", func, false);
elesBound[i].removeEventListener("mouseup", func, false);
}
elesBound = [];
};
document.getElementById("removeListeners").addEventListener("click", function () {
deleteListeners(window);
});
addListeners(window);
基本上我保留了一个列表来跟踪哪些元素绑定到 func,然后在 deleteListeners 上将它们全部解除绑定。
您将在控制台中看到的示例:
addListeners
associateListener
func from ele: DIV(id: d2)
associateListener
func from ele: DIV(id: d2)
associateListener
func from ele: DIV(id: d2)
associateListener
func from ele: DIV(id: d1)
associateListener
func from ele: DIV(id: d1)
associateListener
func from ele: DIV(id: d1)
associateListener
func from ele: BUTTON(id: removeListeners)
associateListener
func from ele: BUTTON(id: removeListeners)
associateListener
deleteListeners
在此之后(何时deleteListeners
被调用),您可以单击任意位置,associateListener
并且func
不会调用您的 和 ,因为所有事件侦听器都将被删除。