This article describes the compatible writing of JS event addition and removal. Share it for your reference, 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; } } }} ;Among them, the addHandler and removeHandsler methods first detect whether there is a DOM2-level method in the passed element. If there is a DOM2-level method, use this method: the incoming event type, the event handler function and the third parameter fasle (representing the bubble stage). If there is an IE method, adopt the second solution. 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). At this time, we use square bracket syntax to specify the attribute name as the event handler, or set the attribute to null.
You can use EventUtil objects like the following:
var btn = document.getElementById("myBtn");var handler = function(){ alert("Clicked");};EventUtil.addHandler(btn , "click", handler);//Omit other codes EventUtil.removeHandler(btn, "click", handler);For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.