This article mainly introduces the cross-browser addition and deletion of event binding functions in JavaScript. It uses pure javascript to implement jquery bind and unbind addition and deletion of event binding techniques, which has good browser compatibility, for more information about how to add and delete event binding functions across browsers using JavaScript, see the following example. Share it with you for your reference. The details are as follows:
The event binding function of IE is attachEvent, while Firefox and Safari are addEventListener, and Opera supports both. With jQuery, you can use a simple bind () or $ (). click () and other functions. If you do not use the JavaScript framework, you can use the following encapsulated bind () function.
Add bind event ()
/************************************ Add events bind * @ param obj: element * @ param type: event name. Do not add "on ". for example, "click" instead of "onclick ". * @ param fn: event processing function ************************************/ function bind (obj, type, fn) {if (obj. attachEvent) {obj ['E' + type + fn] = fn; obj [type + fn] = function () {obj ['E' + type + fn] (window. event);} obj. attachEvent ('on' + type, obj [type + fn]);} else obj. addEventListener (type, fn, false );}
For example, add a click event to the document:
var fn=function(){ alert("Hello, World!!");};bind(document,"click", fn);
Delete event binding unbind ()
Unbind () for the above bind () function
/************************************ Delete an event bind * @ param obj: element * @ param type: event name. Do not add "on ". for example, "click" instead of "onclick" * @ param fn: event processing function ************************************/ function unbind (obj, type, fn) {if (obj. detachEvent) {obj. detachEvent ('on' + type, obj [type + fn]); obj [type + fn] = null;} else obj. removeEventListener (type, fn, false );}
For example, delete the first bound document click event:
The Code is as follows:
Unbind (document, "click", fn );
I hope this article will help you design javascript programs.