A detailed explanation of jquery event binding usage (with the difference between bind and live) _jquery

Source: Internet
Author: User
Tags cbtn

The example of this article analyzes the jquery event binding usage. Share to everyone for your reference, specific as follows:

Html:

<a href= "#" onclick= "addbtn ()" >addBtn</a>
<div id= "MDiv" >
  <button class= "cbtn" onclick = "alert (11111)" >button1</button>
  <button class= "cbtn" >button2</button>
  <button class= "cbtn" >button3</button>
</div>

Javascript:

<script type= "Text/javascript" >
 function addbtn () {
   $ (' #mDiv '). Append (' <button class= ' cbtn ' > Button5</button> ')
 }
jQuery (function ($) {
//use on to replace live and delegate (live is abandoned for performance reasons and replaced by delegate) The button that is added to the mdiv still has the bound event
$ (' #mDiv '). On (' click ', '. Cbtn ', function (index, eledom) {
alert ($ (this). HTML ())
 });
Use
on instead of bind $ ('. Cbtn '). On (' click ', Function () {
alert ($ (this). html ())
 })
//NOTE:/
*
1, regardless of the use of BIND, on, delegate, click (function ()) are repeated binding, that is, the binding of the same type of event is placed in an event queue, executed sequentially, after the bound event does not replace the previously bound, for on use off, Delegate use Unbind to unbind with Undelegate,bind and click, for example, unbind (type) is passed as event type, and all event bindings are solved without passing a type Note that the element itself cannot be unbind (such as Button1)
2, to bind custom events, such as ' open ', which can be used, but activation requires the use of the trigger
summary: It
is recommended that the on function be used, The binding form is $ ('. MyClass '). On ({
click:function (eledom) {
... do someting ...
},
dbclick:function ( Eledom) {
... do someting ...
}
....
})
*/
}
</script>

Some notes:

Bind (TYPE,[DATA],FN) Bind event handlers for specific events for each matching element

Copy Code code as follows:
$ ("a"). Bind ("click", Function () {alert ("OK");});

Live (TYPE,[DATA],FN) attaches an event handler function to all matching elements, even if the element is added later
Copy Code code as follows:
$ ("a"). Live ("Click", Function () {alert ("OK");});

Delegate (SELECTOR,[TYPE],[DATA],FN) specifies an element (which is a child of the selected element) to add one or more event handlers, and to specify which functions to run when these events occur
Copy Code code as follows:
$ ("#container"). Delegate ("A", "click", Function () {alert ("OK");})

on (EVENTS,[SELECTOR],[DATA],FN) an event handler that is bound to one or more events on the selection element

Difference:

. Bind () is directly bound to the element

Live () is bound to an element in a bubbling manner. More appropriate to the list type, bound to the document DOM node. and. Bind () is the advantage of supporting dynamic data.

. Delegate () is a more precise, small-scale use of event proxies, with superior performance. Live ()

. On () is the latest version 1.9 that consolidates the new event binding mechanism in the previous three ways

Add: The difference between bind and live

There are three ways to bind events in jquery: Take the Click event as an example

(1) Target.click (function () {});

(2) Target.bind ("Click", Function () {});

(3) target.live ("Click", Function () {});

The first method is very good understanding, in fact, and ordinary JS usage is similar, just one less on

The second to third method is the binding event, but the two are very different, the following highlights, because this if the use of the framework of jquery is very much, especially to pay attention to the difference between the two.

"The difference between bind and live"

Live method is actually a variant of the Bind method, its basic function is the same as the function of the Bind method, is to bind an event for an element, but the bind method can only give the current existing element binding events, for the subsequent use of JS, such as the new generated element is invalid, While the live method compensates for this flaw in the bind method, it can also bind the corresponding events to the resulting elements. So how is this feature of the live method implemented? Here's how to implement the principle.

The reason why the live method can bind the corresponding events to the later generated elements is attributed to the "event delegate", which means that events bound on ancestor elements can be used on their descendant elements. The processing mechanism of the live method is to bind the event to the root node of the DOM tree rather than to bind directly to an element. Give an example to illustrate:

$ (". ClickMe"). Live ("click", fn);
$ ("Body"). Append ("<div class= ' ClickMe ' > Test live Method Steps </div>");

When we click on this new element, the following steps occur in sequence:

(1) Generate a click event, passed to the div to do the processing

(2) Since no events are directly bound to the Div, the event bubbles directly onto the DOM tree

(3) event bubbling until the root node of the DOM tree, by default, the Click event is bound on the root node

(4) Perform a live-bound click event

(5) Detects whether the object that binds the event exists, and whether the bound event needs to be continued. The detection event object is detected by the

Copy Code code as follows:
$ (event.target). Closest ('. ClickMe ')
can find a matching element to implement.

(6) Pass (5) The test, if the object that binds the event exists, executes the bound event.

Because the live method only detects the existence of the object that binds the event when the event occurs, the live method can implement the new element and bind the event later. In contrast, bind determines whether an element of a bound event exists at the binding stage, and only binds to the current element, not to the parent node.

According to the analysis above, the benefits of live are really great, so why use the Bind method? The reason jquery retains the bind method instead of using the live method instead of bind is because live is not a complete replacement for bind in some cases. The main differences are as follows:

(1) The Bind method can bind any JavaScript event, while the live method only supports click, DblClick, KeyDown, KeyPress, Keyup,mousedown, MouseMove, jQuery1.3. Mouseout, MouseOver, and MouseUp. In the jquery 1.4.1, the focus and blue events are even supported (mapped to more appropriate and bubbling focusin and focusout). In addition, hover (mapped to "MouseEnter MouseLeave") can also be supported in the jquery 1.4.1.

(2) Live () does not fully support elements found by means of the DOM traversal. Instead, you should always use the. Live () method immediately after a selector.

(3) When an element uses the live method to bind the event, if you want to prevent the event from passing or bubbling, return false in the function, just call stoppropagation () is not able to prevent the event from passing or bubbling

More about jquery event and method related content readers can view the site topics: "JQuery common event usage and skills summary"

I hope this article will help you with the jquery program design.

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.