The examples in this article describe the JavaScript implementation of Cross-browser Add and remove event binding functions. Share to everyone for your reference. Specifically as follows:
The event-binding function of IE is attachevent, while Firefox, Safari is Addeventlistener;opera, both are supported. Using jquery, you can use a simple bind (), or a function such as $ (). Click (), and if you don't use the JavaScript framework, you use the following encapsulated bind () function.
Add event bind bind ()
/************************************
* Add Event binding
* @param obj : element
* @param type: Event name to bind the event. "On" is not added. such as: "Click" rather than "onclick.
" * @param fn : event handler
************************************/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 bind () function above
/************************************
* Delete Event binding
* @param obj: the element
* @param type: event name to delete the event. "On" is not added. such as: "Click" instead of "onclick"
* @param fn: event handler
************************************/function
unbind (obj, Ty PE, 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:
Copy Code code as follows:
Unbind (document, "click", FN);
I hope this article will help you with your JavaScript programming.