Event Binding in jquery

Source: Internet
Author: User

First, preface

In the recent project to use jquery to bind events, the first thought is $ (selector). event name (); This way of binding an event, which binds the event, is actually the bind () method, but when the selector matches too many elements, $ (selector). Event name ( ); iterative binding of each element can affect performance. In addition to the ability to bind events in this way, there are live () (expired), delegate (), on () method binding events, then analyze their differences, and which is the most recommended way to use it. Because the live () method has expired, only analysis of the other three, welcome to shoot bricks, spit groove ~ ~ ~

Second, usage and difference

Prepare a example for different methods of binding event testing and comparison.

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>On (), delegate (), bind () event binding test</title>    <Linkrel= "stylesheet"type= "Text/css"href= "Bootstrap.css"></Head><Body>    <Divstyle= "width:800px;margin:50px auto;">        <Bottonclass= "Btn btn-success"ID= "BTN">Add a P element</Botton>        <P>1</P>        <P>2</P>    </Div>    <Scripttype= "Text/javascript"src= "Jquery.js"></Script>    <Scripttype= "Text/javascript">$ (document). Ready (function(){            $('#btn'). Click (function(){                $('Div'). Append ('<p> Add a P element </p>');        });    }); </Script></Body></HTML>

Next, bind the click event to all P elements, such as:

Bind () Method: Adds one or more event handlers for the selected element, and specifies the function to run when the event occurs.

How to use $ (selector). bind (Event,data,function)

Event required. Specifies one or more events that are added to an element. Multiple events are separated by a space. Must be a valid event.

data is optional. Specifies additional data that is passed to the function.

function required. Specifies the function to run when an event occurs.

function () {    alert (this). Text ());});

This binds the Click event to all P elements, and then pops up the content when clicked. But there are two problems,

First, the implicit iterative approach is used, and if the number of elements to be matched is particularly high, such as if I put 10 p elements in the Div, I have to perform a binding 10 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 click Response.

Another way of writing the Bind () method is:

$ (' div p '). Click (function() {    alert (this). Text ());
});

Delegate () Method: Adds one or more event handlers for the specified element (which is a child of the selected element), and specifies the function to run when these events occur, and an event handler that uses the delegate () method applies to the current or future element (such as a new element created by the script).

How to use: $ ( selector). Delegate ( Childselector, Event, Data, function)

Childselector required. Specifies one or more child elements to attach the event handler.

Event required. Specifies one or more events that are attached to an element. Multiple event values are separated by a space. Must be a valid event.

data is optional. Specifies additional data that is passed to the function.

function required. Specifies the function to run when an event occurs.

function () {     alert (this). Text ());});

The delegate () mode is based on the mechanism of the event delegation, not the P element directly binding the point-and-click event, but the binding of the fixed-point event for its parent element (or ancestor element), and when any P element is clicked, the event will bubble up until the element of the bound event, when the object captured by the event stream matches the selector The alert ($ (this). Text ()) is executed; the code.

So using the delegate () method solves the above two problems with the bind () method, eliminating the need to bind events for each P element, or binding events for dynamically added P elements. Although the binding is implemented, there may be problems with the call. If the event target is in a deep position in the DOM tree, this layer bubbles up to find the element that matches the selector, and it affects performance.

On () method: 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.;

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

Data: Optional; parameters to be passed;

function: required; functions that need to be executed when a binding event occurs;

function () {     alert (this). Text ());});

The effect of the On () method is the same as the delegate () method, and by looking at the jquery source you will find that either bind () or delegate () is actually implemented by the on () method, except that the parameters are different. The source code for three methods (JQuery Source Viewer) is as follows:

JQuery.fn.bind =function(types, data, fn) {return  This. On (types,NULL, data, FN);        }; JQuery.fn.delegate=function(selector, types, data, fn) {return  This. On (types, selector, data, FN);        }; JQuery.fn.on=function(types, selector, data, Fn,one) {varORIGFN, type; //Types can be a map of Types/handlers            if(typeoftypes = = = "Object") {                //(Types-object, selector, data)                if(typeofSelector!== "string") {                    //(types-object, data)data = Data | |selector; Selector=undefined; }                 for(Typeinchtypes) {                     This. On (type, selector, data, Types[type], one); }                return  This; }            if(Data = =NULL&& fn = =NULL) {                //(types, fn)fn =selector; Data= Selector =undefined; } Else if(fn = =NULL) {                if(typeofselector = = = "string") {                    //(types, selector, fn)fn =data; Data=undefined; } Else {                    //(types, data, FN)fn =data; Data=selector; Selector=undefined; }            }            if(fn = = =false) {fn=Returnfalse; } Else if(!fn) {                return  This; }            if(One = = 1) {ORIGFN=fn; FN=function(event) {//Can Use an empty set, since event contains the infojQuery (). Off (event); returnOrigfn.apply ( This, arguments);                }; //Use same GUID so caller can remove using ORIGFNFn.guid = Origfn.guid | | (Origfn.guid = jquery.guid++); }            return  This. each (function() {JQuery.event.add ( This, types, FN, data, selector);        }); };

jquery officially recommends the use of the On () binding event.

Iii. Summary

When the selector matches a long time, do not use bind () to iterate the binding, can affect the performance, with the ID selector, the use of bind (), simple and convenient; To bind events to dynamically added elements, using delegate () or on (), the official recommendation is to use on ().

If you want to reprint this article, please specify the source: http://www.cnblogs.com/changjianqiu/

Event binding in 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.