Similarities and Differences of Binding Events in jquery

  • 2021-07-24 10:01:17
  • OfStack

Talking about how bind (), live (), delegate (), on () bind events in jquery

1. Bind ()

$(selector).bind(event,data,function)

Event: Required; One or more events added to the element.

Data: Optional; Parameters to pass

Function: Required; The function that needs to be executed when the binding event occurs;

Defining Events:

$(selector).bind({event1:function, event2:function, ...});

2.live()

$(selector).live(event,data,function)

Event: Required; 1 or more events added to an element

Data: Optional; Parameters to pass

Function: Required; The function that needs to be executed when the binding event occurs;

Defining Events:

$(selector).live({event1:function, event2:function, ...}) 

3.delegate()

$(selector).delegate(childSelector,event,data,function)

childSelector: Required; Elements that need to add event handlers, 1 is generally a child element of selector;

event: Required; 1 or more events added to an element

Data: Optional; Parameters to pass

Function: Required; The function that needs to be executed when the binding event occurs;

Defining Events:

$(selector).delegate(childselector,{event1:function, event2:function, ...})

4.on()

$(selector).on(event,childselector,data,function)

childSelector: Required; Elements that need to add event handlers, 1 is generally a child element of selector;

event: Required; 1 or more events added to an element

Data: Optional; Parameters to pass

Function: Required; The function that needs to be executed when the binding event occurs;

Defining Events:

$(selector).on({event1:function, event2:function, ...},childselector); 

Similarities, differences, advantages and disadvantages of the four methods

Similarities:

1. Both support the binding of unit multiple events; Spaces are separated or braces are used instead;

2. Events are transmitted to document for event response through event mode;

Compare:

1. The bind () function can only set events for existing elements; However, live (), on () and delegate () all support the event setting of newly added elements in the future;

2. bind () function was highly respected before jquery version 1.7. After version 1.7 came out, bind () was not officially recommended, and the substitute function was on (), which is also a newly added function in version 1.7. Similarly, it can be used to replace live () function, and live () function has been deleted in version 1.9.

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


Related articles: