Event bindings typically occur in onload or Domcontentready, where event binding takes up processing time to consume memory, and not every event is clicked to execute.
This event delegate can optimize the event binding behavior.
Events bubble-level until they are captured by a parent element. The event proxy binds a processing event to the outer element, and it can handle all events on the child element.
Three stages of DOM standard events:
Capture
Reach the target,
Bubble
IE does not support capture, but bubbling is enough.
The element in which the Event.currenttarget event handler is currently processing the event
Event.target the real goal of the event
Event.type Departure Event Type//click MouseOver mouseout
This is always equal to Currenttarget, and Target contains only the actual target of the event
var btn = document.getElementById (' mybtn ');
Btn.onclick = function (event) {
Alert (Event.currenttarget = = = this); True
Alert (Event.target = = this); True
}
If the event handler exists in the parent node of the button, these values are different
Document.body.onclick = function (event) {
Alert (Event.currenttarget = = = Document.body); True
Alert (This = = = Document.body);//True
Alert (Event.target = = = document.getElementById (' mybtn ')); True
}
For example:
<body>
<div> <a href= "" >btn</a></div>
<div> <a href= "" id= "DoSomething" >btn</a></div>
<div> <a href= "" id= "Gowhere" >btn</a></div>
</body>
-----------------------------------------------
Document.getelementbytagname (' body '). onclick = function (e) {
Browser target
E = e | | window.event;
var target = E.target | | E.srcelement;
if (target.nodename!== ' A ') {return; }
if (target.id = = ' dosomething ') {
Alert (' dosomething ');
} else if (target.id = = ' Gowhere ') {
Alert (' Gowhere ');
} else {
Alert (' Other A click ');
}
if (typeof E.preventdefault = = = ' function ') {
E.preventdefault ();
E.stoppropagation ();
} else {
E.returnvalue = false;//ie Default True false cancels the default behavior of an event
E.cancelbubble = true;//ie default false, but set true to cancel event bubbling
}
}
JavaScript Binding Event Delegate Demo