This article describes the usage of the JavaScript event model. Share it for your reference. The specific analysis is as follows:
1. Event model
Bubbling: Events are passed from leaf nodes along the ancestor node to the root node upwards.
Capturing: From the top element of the DOM tree to the most accurate element, opposite to the bubble event
DOM standard event model: The DOM standard supports both bubble-type events and capture-type events. It can be said to be a combination of the two, first of all, capture-type, and then bubble-type transmission.
2. Event Object
In IE browser, event object is a property of window. In the DOM standard, event must be passed to event processing function as a unique parameter.
Obtain a compatible event object:
function(event){ //event is a processing function passed as a parameter of the DOM standard event = event ?event : window.event; }In IE, the object of the event is contained in the srcElement of the event, while in the DOM standard, the object is contained in the target property
Obtain the element pointed to by a compatible event object:
var target =event.srcElement ? event.srcElement : event.target ;
The premise is to ensure that the event object has been correctly obtained
3. Event listener
Under IE, the registered listener executes in reverse order, that is, the registered listener is executed first.
element.attachEvent('onclick',observer); //Register listener element.detachEvent('onclick',observer) //Remove listenerThe first parameter is the event name, and the second is the callback processing function
Under DOM standard:
element.addEventListener('click',observer,useCapture) element.removeEventListener('click',observer,useCapture)The first parameter is the event name, without the prefix of "on", the second parameter is the callback processing function, and the third parameter indicates whether the callback function is called in the capture stage or in the bubble stage. The default true is the capture stage
4. Event delivery
Cancel event delivery in the browser compatible
function someHandler(event){ event = event || window.event; if(event.stopPropagation) //DOM standard event.stopPropagation(); else event.cancelBubble = true; //IE standard}Cancel the default processing after event delivery
function someHandler(event){ event = event || window.event; if(event.preventDefault) //DOM standard event. preventDefault (); else event.returnValue = true; //IE standard}I hope this article will be helpful to everyone's JavaScript programming.