Event delegates in JS and jquery

Source: Internet
Author: User

"Go + own Changes"

Concept:

What is an event delegate: Popular, the event is onclick,onmouseover,onmouseout, and so is the event, entrusted, is to let others do, this event is added to some elements, but you add to others to do, complete this event.
For example: Three colleagues are expected to receive a courier in Monday. For the Signature Express, there are two ways: one is three people at the door of the company and other courier, the second is entrusted to the front desk mm for sign. In reality, most of US use commissioned programs (the company will not tolerate so many employees standing at the door to wait for courier). The front desk mm received the courier, she will determine who the recipient, and then according to the recipient's request for sign, or even on behalf of payment. This solution also has an advantage, that is, even if the company's new employees (regardless of how much), the front desk mm will be sent to the new staff after The courier to verify and sign on behalf of.

Principle:

Using the bubbling principle, the event is added to the parent, triggering the execution effect.

Role:

1. Better performance
2. For newly created elements, you can have an event directly

Event Source:

Same as this (he does not have to look at the problem, who is the person who operates), the event object under the

Usage scenarios:

• Bind the same events for many elements in the DOM;
• Bind events to elements that do not already exist in the DOM;

JS's event delegate:

Benefits: 1, improve performance.

We can look at an example: the need to trigger each Li to change their background color.

<ulID= "ul">  <Li>Aaaaaaaa</Li>  <Li>bbbbbbbb</Li>  <Li>Cccccccc</Li></ul>
function () {  var oul = document.getElementById ("ul");   var aLi = oul.getelementsbytagname ("li");    for (var i=0; i<ali.length; i++) {    function() {      this . Style.background = "Red";    }     function () {      this. Style.background = "";}}  } 

This allows us to add mouse events on top of Li.

But if we could have a lot of Li with a for loop, that would affect performance.

Here we can use the event delegate to achieve this effect. The HTML does not change.

Window.onload =function(){  varOul = document.getElementById ("ul"); varALi = Oul.getelementsbytagname ("li");/*The event source is used here: The event object, the source, regardless of the event, as long as the element you are manipulating is the source of the event. Ie:window.event.srcElement Standard: Event.targetnodename: Find the label name of the element*/Oul.onmouseover=function(EV) {varEV = EV | |window.event; vartarget = Ev.target | |ev.srcelement; //alert (target.innerhtml);    if(target.nodeName.toLowerCase () = = "Li") {Target.style.background= "Red"; }} oul.onmouseout=function(EV) {varEV = EV | |window.event; vartarget = Ev.target | |ev.srcelement; //alert (target.innerhtml);    if(target.nodeName.toLowerCase () = = "Li") {Target.style.background= ""; }  }}

Benefit 2, the newly added element will also have previous events.

We also take this example, but we want to do dynamic add Li. Click button to add Li dynamically

Such as:

<input type= "button" id= "btn"/><ul id= "ul" >  <li>aaaaaaaa</li>  <li>bbbbbbbb </li>  <li>cccccccc</li></ul>

We will do this without an event delegate:

Window.onload =function(){  varOul = document.getElementById ("ul"); varALi = Oul.getelementsbytagname ("li"); varOBTN = document.getElementById ("btn"); varInow = 4;  for(vari=0; i<ali.length; i++) {Ali[i].onmouseover=function(){       This. Style.background = "Red"; } ali[i].onmouseout=function(){       This. Style.background = ""; }} Obtn.onclick=function() {Inow++; varOLi = document.createelement ("li"); Oli.innerhtml= 1111 *Inow;  Oul.appendchild (OLi); }  }

In doing so we can see the click button on the newly added Li with no mouse-over events to change their background color.

Because the FOR loop has been executed when you click Add.

Then we do it in the way of the event delegate. Is that HTML does not change

Window.onload =function(){  varOul = document.getElementById ("ul"); varALi = Oul.getelementsbytagname ("li"); varOBTN = document.getElementById ("btn"); varInow = 4; Oul.onmouseover=function(EV) {varEV = EV | |window.event; vartarget = Ev.target | |ev.srcelement; //alert (target.innerhtml);    if(target.nodeName.toLowerCase () = = "Li") {Target.style.background= "Red"; }} oul.onmouseout=function(EV) {varEV = EV | |window.event; vartarget = Ev.target | |ev.srcelement; //alert (target.innerhtml);    if(target.nodeName.toLowerCase () = = "Li") {Target.style.background= ""; }} Obtn.onclick=function() {Inow++; varOLi = document.createelement ("li"); Oli.innerhtml= 1111 *Inow;  Oul.appendchild (OLi); }}

Ok:

As in our microblog, the new tweet still has previous mouse events.

Event Delegation for jquery

 $ (function   () {$ ( ' #ul1, #ul2 '). Delegate (' Li ', ' click ', function   () { Span style= "color: #0000ff;" >if  (!$ ( Span style= "color: #0000ff;"         >this ). css (' background ', ' Red '  true  );   else   {$ ( this ). css (' background ', ' #fff '  ); }     }) });

The newest on () method takes the delegate () method

$(function(){         $(' #ul1, #ul2 '). On (' Click ', ' Li ',function(){                 if(!$( This). attr (' s ')) {                 $( This). CSS (' background ', ' red '); $( This). attr (' s ',true); }Else {                         $( This). CSS (' background ', ' #fff '); $( This). Removeattr (' s '); }         }) });

Recommended development using the latest version of jquery and using the latest version of the method

Event delegates in JS and jquery

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.