jquery event bindings on (), Bind (), Live () and delegate () methods

Source: Internet
Author: User

jquery Event Binding has four methods, corresponding to On,off,bind,unbind,delegate,undelegate,live,die

Compare and Contact:


The 1.bind () function can only set events for elements that already exist, but live (), on (), delegate () Support event settings for new additions in the future;

2.bind () function in the jquery1.7 version before the comparison is respected, after the 1.7 version, the official has not recommended bind (), the substitution function is on (), this is also the 1.7 version of the newly added function, again, you can

To replace the live () function, the live () function has been deleted in version 1.9;

The 3.live () function is similar to the delegate () function, but the live () function is less delegate () in terms of execution speed, flexibility, and CSS selector support.

4. Version bind () supports all versions of jquery; Live () supports jquery1.8-;delegate () support for Jquery1.4.2+;on () support jquery1.7+; 

Specific as follows:

. Bind ()

$ (' a '). bind (' click ', function () {alert ("that Tickles!")});

This is the simplest way to bind. jquery scans the document to find all the $ (' a ') elements and binds the alert function to each element's click event, but here are two questions:
First, the implicit iterative approach is used, and if the number of elements to be matched is particularly high, such as if I put 50 p elements in the Div, I have to perform a binding 50 times. For a large number of elements, performance is affected. But if the ID selector, because the ID is unique, with the bind () method is very fast.
The second problem is that you cannot bind to an element that does not already exist. Click on the button on the page, will dynamically add a P element, click on this P element, you will find no action response.

. Live ()(not recommended)

$ (' a '). Live (' click ', function () {alert ("that Tickles!")});

jquery binds the alert function to the $ (document) element and uses ' click ' and ' a ' as arguments. Whenever an event bubbles onto the document node, it checks to see if the event is a click event, and whether the target element of the event matches the CSS selector of ' a ', and if so, executes the function.

The live method can also be bound to a specific element (or context) rather than document, like this:

$ (' A ', $ (' #container ') [0]). Live (...);

In order to solve these two problems, the delegate method can be used.

. Delegate ()

$ (' #container '). Delegate (' A ', ' click ', function () {alert ("that Tickles!")});

The jquery scan document looks for $ (' #container ') and binds the alert function to $ (' #container ') using the Click event and the CSS selector ' a ' as a parameter. Whenever an event bubbles to $ (' #container '), it checks to see if the event is a click event, and whether the target element of the event matches the CCS selector. If the results of both checks are true, it executes the function.

It can be noted that this process is similar to. Live (), but it binds handlers to specific elements rather than to the root of document. The savvy JS ' er may have made the conclusion that $ (' a '). Live () = = $ (document). Delegate (' A '), is that right? Well, no, not exactly.

Why. Delegate () is better than. Live ()

For several reasons, people are often more inclined to opt for the delegate method of jquery than the live method. Consider the following example:

$ (' a '). Live (' click ', function () {blah ()});
Or
$ (document). Delegate (' A ', ' click ', function () {blah ()});

Speed

The latter is actually faster than the former, because the former first has to scan the entire document to find all the $ (' a ') elements and save them as jquery objects. Although the live function only needs to pass ' a ' as a string argument for subsequent judgment, the $ () function does not know that the method being linked will be. Live ().

On the other hand, the delegate method only needs to find and store the $ (document) element.

One way to avoid this problem is to call live that is bound outside of (document). Ready () so that it executes immediately. In this way, it runs before the DOM gets populated, so it doesn't look for elements or create jquery objects.

Flexibility and chain capability

The live function is also quite confusing. Think of it as being chained to the set of $ (' a ') objects, but it actually works on the $ (document) object. For this reason, it can try to link the method to itself in a way that scares the dead. In fact, what I want to say is, with $.live (' a ',...) This form is a global jquery approach, and the live approach makes more sense.

Only CSS selectors are supported

Finally, there is a big drawback to the live approach, which is that it can only operate on a direct CSS selector, which makes it very inflexible.  

. On ()

 

On () adds one or more event handlers for the specified element, and specifies the function to run when these events occur. Event handlers that use the on () method apply to current or future elements, such as new elements created by a script.

How to use

$ (selector). On (Event,childselector,data,function)

Event: Required item; One or more events added to the element, such as Click,dblclick, etc.;   

Single Event handling: For example $ (selector). On ("click", Childselector,data,function);

Multi-Event Processing: 1. Use spaces to separate multiple events, such as $ (selector). On ("Click Dbclick mouseout", childseletor,data,function);

2. Use braces to flexibly define multiple events, such as $ (selector). On ({event1:function, event2:function, ...},childselector);

3. Space Separation Method: Binding is more rigid, can not give the event of a separate binding function, suitable for handling multiple events call the same function;

Brace substitution: The binding is more flexible and can be used to bind functions individually;

  childselector: Optional; an element that needs to add an event handler, typically a selector child element;

data: optional; parameters to be passed;

function : required and functions to be executed when a binding event occurs

Cases:

$ (function () {             /********* adds a single event to handle *********/24             $ (". Header"). On ("click", ". Btn-test", function () {26                 //Show hidden div27                 $ (". Container"). Slidetoggle ()             /******** Add multiple event handling ********/31             // Spaces are separated             by $ (". Header"). On ("Mouseout click", ". Btn-test", function () {                 //Show hidden div35                 $ (". Container"). Slidetoggle (); (())             ; the PNs             //curly braces are substituted in the form of             $ (". Header"). On ({                 "mouseout": function () {                     Alert ("This is the Mouseout event!");                 },43                 "click": Function () {                     $ (". Container"). Slidetoggle ();                 }46             }, ". Btn-test"); 47             //Delete event             $ (". Header"). Off ("click", ". Btn-test");         

Summarize:

1. The selector matches the elements more than a few, do not use bind () iteration binding

2. When using the ID selector, bind () can be used

3. You need to bind the dynamically added elements with delegate () or on ()

4. Using the delegate () and on () methods, the DOM tree is not too deep

5. Use on () as much as possible

jquery event bindings on (), Bind (), Live () and delegate () methods

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.