JavaScript Event Delegation Technology example analysis _javascript skills

Source: Internet
Author: User

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

If a whole page has a lot of buttons. We're going to bind the event handlers for each button. This will affect performance.

First, each function is an object, and the object consumes a lot of memory. The more objects in memory, the worse the performance.

Second, the number of DOM accesses increases, which results in a delay in loading the page. In fact, there is a good solution to how to use a good event handler.

Event delegate:

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

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

We can bind an event handler 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're going to bind the event handlers for these 3 li ...

Only need in the UL binding event handler.

Obj.eventhandler ($ ("MyList"), "click", Function (e) {
  e = e | | window.event;
  Switch (e.target.id) {
//Everyone should remember that target is the event target,
///The corresponding alert will pop up as soon as the target element of the event is clicked.
 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 event delegate is very useful.

If this is not the case, one way to bind it is to count the countless event handlers.

I hope this article will help you with your JavaScript programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.