Examples of compatible writing for adding and removing JS events, and examples of js removing writing
This article describes how to add and remove JS events. We will share this with you for your reference. The details are as follows:
var EventUtil = { addHandler : function (element , type, handler { if ( element.addEventListener){ element.addEventListener(type, handler, false); }else if ( element.attachEvent) { element.attachEvent("on"+type,handler); }else { element["on" + type] = handler; } }, getEvent : function (event){ return event ? event : window.event; }, preventDefault : function(event){ if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue = false; } }, removeHandsler : function (element , type , handler){ if(element.removeEventListener){ element.removeEventListener(type , handler , false); }else if(element.detachEvent){ element.detachEvent("on" + type , handler); }else{ element["on" + type] = handler; } } stopPropagation : function(event){ if(event.stopPropagation){ event.stopPropagation(); }else { event.cancelBubble = true; } }, getRelatedTarget : function(event){ if(event.relatedTarget){ return event.relatedTarget; }else if (event.toElement){ return event.toElement; }else if(event.fromElement){ return event.fromElement; }esle { return null; } }, getButton : function (event){ if(document.implementation.hasFeature("MouseEvents" , "2.0")){ return event.button; }else{ switch(event.button){ case 0: case 1: case 3: case 5: case 7: return 0; case 2: case 6: return 2; case 4: return 1; } } }} ;
The addHandler and removehandler methods first detect whether there are DOM2-level methods in the input elements. if the DOM2-level method exists, use this method: to pass in the event type, event handler function, and third parameter fasle (indicating the bubble stage ). if the IE method exists, the second solution is adopted. note that the event type must be prefixed with "on. the last possibility is to use the DOM0-level method (in modern browsers, the code here should not be executed ). in this case, we use the square brackets syntax to specify the attribute name as an event handler, or set the attribute to null.
You can use the EventUtil object as follows:
Var btn = document. getElementById ("myBtn"); var handler = function () {alert ("Clicked") ;}; EventUtil. addHandler (btn, "click", handler); // skip other code EventUtil. removeHandler (btn, "click", handler );