Say for example, we don't know how many functions already binded to an event. In that case we开发者_开发知识库 can bind our own function like below
var old = (element.onclick) ? element.onclick : function () {};
element.onclick = function () {old(); myOwn()};
Now how to unbind myOwn function alone without disturbing others?
When attaching multiple events to a DOM element, you should not change the "onfoo" attribute. Rather, use addEventListener("foo")
(or attachEvent("foo")
in IE). Similarly, you have removeEventListener
(detachEvent
in IE) to remove events.
var myEventHandler = function (e) {
alert("do stuff");
}
var myDomElement = document.getElementById("my_id");
myDomElement.addEventListener("click", myEventHandler, true);
myDomElement.attachEvent("click", myEventHandler); // IE
myDomElement.removeEventListener("click", myEventHandler, true);
myDomElement.detachEvent("click", myEventHandler); // IE
Replace "onfoo" with "foo". So when you do element.onmouseup
, you should instead do element.addEventListener("mouseup", ...)
.
It is imperative that you use a function reference, since the internal object ID of the function is used for reference, and not it's contents. This will not work:
myDomElement.addEventListener("click", function () { alert("foo") }, true)
myDomElement.removeEventListener("click", function () { alert("foo") }, true)
You can create a simple wrapper for cross browser compatibility.
var addEventListener = function (element, event, func) {
if (element.addEventListener) {
element.addEventListener(event, func, true);
} else {
element.attachEvent(event, func);
}
}
精彩评论