This article analyzes the JavaScript event delegation technology in an example. Share it for your reference. The specific analysis is as follows:
If there are a large number of buttons in an overall page, we have to bind event handlers for each button. This will affect performance.
First of all, each function is an object, and the object will occupy a lot of memory. The more objects there are in memory, the worse the performance.
Secondly, the increase in the number of dom visits will cause the page to be loaded late. In fact, there are still good solutions to how to make good use of event handlers.
Event delegation:
The solution to the problem of too many event handlers is event delegation technology.
Event delegate technology takes advantage of event bubbles. Just specify an event handler.
We can bind event handlers for a parent element that needs to trigger an event.
<ul id="mylist"> <li id="li_1">sdsdsd</li> <li id="li_2">sdsdsd</li> <li id="li_3">sdsdsd</li></ul>
Now we want to bind event handlers for these 3 lis...
Just bind the event handler in ul.
obj.eventHandler($("mylist"),"click",function(e){ e = e || window.event; switch(e.target.id){//Everyone should still remember that target is the event target, //As long as the target element of the event is clicked, the corresponding alert will pop up. 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 this method is not adopted, binding one by one will be endless event handlers.
I hope this article will be helpful to everyone's JavaScript programming.