Home > Article > Web Front-end > Introduction and use of EventUtil.addHandler
addHandler method
His accusation is that the DOM0 level method, DOM2 level method or IE method is used to add events. This method belongs to an object named EventUtil, which can be used to handle differences between browsers. The addHandler() method accepts 3 parameters: the element to operate on, the time name and the event handler function.
The method corresponding to the addHandler() method is removeHandler(), which also accepts the same parameters. The purpose of this method is to remove the previously added event handler --- regardless of how the event handler was added to the element. If other methods are invalid, the DOM level 0 method is used by default.
The method corresponding to the addHandler() method is removeHandler(), which also accepts the same parameters. The purpose of this method is to remove the previously added event handler --- regardless of how the event handler was added to the element. If other methods are invalid, the DOM level 0 method is used by default.
//EventUtilvar EventUtil = { addHandler: function (element, type, handler) {if (element.addEventListener) { //DOM2级 element.addEventListener(type, handler, false); } else if (element.attachEvent) { //DOM1级 element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; //DOM0级 } }, removeHandler: function (element, type, handler) { //类似addHandlerif (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } } }var btn1 = document.getElementById("myBtn1");var handler = function () { alert("hello handler"); } EventUtil.addHandler(btn1, "click", handler);
Usage:
The method first checks the DOM2-level method. If the DOM2-level method exists, use this method: pass in the event type, event processing program, and the third parameter false (indicating the bubbling stage).
If there is an IE method, adopt the second option. (Note that in order to run in IE8 and earlier versions, the event type must be prefixed with "on" .)
The last possibility is to use the DOM0 level method. At this point, we are using bracket syntax to specify the property name as the event handler , or set the event to null.
The above is the detailed content of Introduction and use of EventUtil.addHandler. For more information, please follow other related articles on the PHP Chinese website!