Home >Web Front-end >JS Tutorial >JavaScript event model example analysis_javascript skills
The examples in this article describe the usage of the JavaScript event model. Share it with everyone for your reference. The specific analysis is as follows:
1. Event model
Bubbling events: Events are propagated from leaf nodes along ancestor nodes to the root node
Capturing events: from the top element of the DOM tree to the most precise element, as opposed to bubbling events
DOM standard event model: The DOM standard supports both bubbling events and capture events. It can be said to be a combination of the two. First, the capture type, and then bubbling delivery
2. Event object
In IE browser, the event object is an attribute of window. In the DOM standard, event must be passed as the only parameter to the event processing function
Get compatible event object:
function(event){ //event 是作为DOM标准的参数传入处理函数 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 attribute
Get the element pointed to by the 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, registered listeners are executed in reverse order, that is, those registered later are executed first
element.attachEvent('onclick',observer); //注册监听器 element.detachEvent('onclick',observer) //移除监听器
The first parameter is the event name, and the second parameter is the callback handler function
Under DOM standard:
element.addEventListener('click',observer,useCapture) element.removeEventListener('click',observer,useCapture)
The first parameter is the event name without the "on" prefix, the second parameter is the callback processing function, and the third parameter indicates whether the callback function is called in the capture phase or the bubbling phase. The default is true in the capture phase.
4. Event delivery
Compatibly cancel browser event delivery
function someHandler(event){ event = event || window.event; if(event.stopPropagation) //DOM标准 event.stopPropagation(); else event.cancelBubble = true; //IE标准 }
Default processing after canceling event delivery
function someHandler(event){ event = event || window.event; if(event.preventDefault) //DOM标准 event. preventDefault (); else event.returnValue = true; //IE标准 }
I hope this article will be helpful to everyone’s JavaScript programming design.