Home  >  Article  >  Web Front-end  >  JavaScript event delegation technology example analysis_javascript skills

JavaScript event delegation technology example analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:15:261029browse

This article analyzes JavaScript event delegation technology with examples. Share it with everyone for your reference. The specific analysis is as follows:

If there are a large number of buttons in a whole page, we need to bind event handlers to each button. This will affect performance.

First of all, every function is an object, and the object will occupy a lot of memory. The more objects in the memory, the worse the performance.

Secondly, an increase in the number of DOM visits will lead to delayed page loading. In fact, there are still good solutions for how to make good use of event handlers.

Event delegate:

The solution to the problem of too many event handlers is event delegation technology.

Event delegation technology takes advantage of event bubbling. Just specify an event handler.

We can bind event handlers to 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 need to bind event handlers for these 3 li's..

Only need to bind the event handler in ul.

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, binding them one by one will result in countless event handlers.

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn