The example in this article describes the JavaScript implementation of cross-browser adding and deleting event binding functions. Share it with everyone for your reference. The details are as follows:
The event binding function of IE is attachEvent; while Firefox and Safari are addEventListener; Opera supports both. Using jQuery, you can use simple bind(), or functions such as $().click() to solve the problem. If you are not using a JavaScript framework, you can use the following encapsulated bind() function.
Add event binding bind()
/************************************ * 添加事件绑定 * @param obj : 要绑定事件的元素 * @param type : 事件名称。不加 "on". 如 : "click" 而不是 "onclick". * @param fn : 事件处理函数 ************************************/ 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 document:
var fn=function(){ alert("Hello, World!!"); }; bind(document,"click", fn);
Delete event binding unbind()
unbind() for the bind() function above
/************************************ * 删除事件绑定 * @param obj : 要删除事件的元素 * @param type : 事件名称。不加 "on". 如 : "click" 而不是 "onclick" * @param fn : 事件处理函数 ************************************/ 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:
I hope this article will be helpful to everyone’s JavaScript programming design.