Before explaining, let’s talk about performance.
If there are a large number of buttons in a whole page, we have to bind event handlers to each button. This will affect the performance.
First of all, each function is an object , the object will occupy a lot of memory. The more objects in the memory, the worse the performance.
Secondly, the increase in the number of dom accesses will lead to delayed page loading. In fact, there are still some problems in how to make good use of event handlers. A very good solution.
1. Event Delegation
The solution to the problem of too many event handlers is event delegation technology.
Event delegation technology uses event bubbling. Just specify one event handler.
We can bind event handlers for a parent element that needs to trigger an event.
HTML code:
<ul id="mylist"> <li id="li_1">sdsdsd</li> <li id="li_2">sdsdsd</li> <li id="li_3">sdsdsd</li> </ul>
Now we have to bind event handlers for these 3 li...
Just need to ul binding event handler.
js code:
obj.eventHandler($("mylist"),"click",function(e){ e = e || window.event; switch(e.target.id){ //大家应该还记得target是事件目标,只要点击了事件的目标元素就会弹出相应的alert. case "li_1": alert("li_1"); break; case "li_2": alert("li_2"); break; case "li_3": alert("li_3"); break } })
If in a complex web application, this kind of event delegation is very practical.
If you don’t use this method, go one by one Binding means countless event handlers.
Okay. That’s it for now.