Previous contact with the event agent, but the impression is not profound. This time write down to strengthen the impression.
Let's use a common code example:
HTML DOM Structure:
<ul id= "UL1" > <li>001</li> <li>002</li> <li>003</li></ Ul>
<script>var oul = document.getElementById (' ul1 '); var aLi = oul.getelementsbytagname (' li '); for (var i = 0, i = ali.length; i++= fn;} </script>
Requirement: If you need to add a click event to each li.
General Implementation method: traverse each Li to give each Li a single click event.
Disadvantages:
1, if the page has a lot of Li, such as portal news site News list. If traversing is required, the comparison affects performance.
2, if the new addition of a li, such as the micro-Bo, just sent to the micro-bo, will not just send the micro-bo on the incident.
For the 2nd: The answer is that the newly created element is not preceded by an event that was traversed, because the Li has been traversed before the element was created, giving an existing Li plus event.
Solution:
In order to solve these two shortcomings, we use the event proxy, also called the event delegate way to implement.
In order to better understand the event delegation, you should first understand the event bubbling knowledge. In this case, I will not say in detail that the event bubbled up.
Depending on the event bubbling or capturing features, we can add click events to ul.
Code:
var Oul = document.getElementById (' ul1 '); Oul.onclick = function (ev) { var ev = EV | | event; Compatible with var target = Ev.target | | ev.srcelement; Find the LI element if (target.nodeName.toLowerCase () = = ' Li ') { //li added event fn ();} }
Summary: Although the EV object has some compatibility, the compatibility process here is not difficult. In fact, the nature of the event delegate is to add events to the parent of multiple groups of elements, then use bubbling or capture to find the following child elements, and then bind the events separately.
JavaScript event Proxy (delegate)