About JS in the event monitoring everyone uses more, but is to determine whether the browser support AddEventListener and attachevent, online search on the event monitoring methods are quite many, but some are not very perfect. The following method is the same for adding event sniffing, except that a little surgery is done on the cancellation of the event bindings and now supports the use of anonymous functions, so you no longer need to name the function separately when binding the event.
Main code:
Copy Code code as follows:
/* Bind event and Unbind * *
var handlehash = {};
var bind = (function () {
if (Window.addeventlistener) {
return function (EL, type, FN, capture) {
El.addeventlistener (type, function () {
FN ();
Handlehash[type] = Handlehash[type] | | [];
Handlehash[type].push (Arguments.callee);
}, capture);
};
else if (window.attachevent) {
return function (EL, type, FN, capture) {
El.attachevent ("On" + Type, function () {
FN ();
Handlehash[type] = Handlehash[type] | | [];
Handlehash[type].push (Arguments.callee);
});
};
}
})();
var unbind = (function () {
if (Window.addeventlistener) {
return function (el, type) {
if (Handlehash[type]) {
var i = 0, len = handlehash[type].length;
for (i; i<len; i + 1) {
El.removeeventlistener (type, handlehash[type][i]);
}
};
};
else if (window.attachevent) {
return function (el, type) {
if (Handlehash[type]) {
var i = 0, len = handlehash[type].length;
for (i; i<len; i + 1) {
El.detachevent ("On" + Type, handlehash[type][i]);
}
};
};
}
})();
Principle Analysis:
Handlehash do hash Table cache event function,handlehash[' event name ' is an array to add multiple event listener methods, unbind which event to traverse handlehash[' event name ' of the array, and then remove.
Use:
Copy Code code as follows:
Bind (obj, ' click ', function () {
Alert (' click ');
});
Unbind (obj, ' click ');