The difference between bind and on in jquery is: on binding has one more childSelector parameter than bind binding. bind can only add events to the element itself that meets the conditions, and on can delegate events of child elements to the parent element for processing.
Environment:
This article applies to all brands of computers.
(Recommended tutorial: jquery video tutorial)
Difference analysis:
bind and on are both used for element binding events, and their maximum The difference is that events bubble up.
Event bubbling is also the prototype of delegated events. Event delegation means entrusting things of the subclass to the parent class. The most intuitive difference is that on binding has one more parameter 'childSelector' than bind binding.
Syntax:
$(selector).on(event,childSelector,data,function)
Parameters:
$(selector).bind(event,data,function,map)
Parameters:
bind can only add events to the elements themselves that meet the conditions. on can delegate events of child elements to parent elements for processing, and can add binding events to dynamically added elements.
That is, for newly added elements If the element is bound on, new elements that meet the conditions will also be bound to the event. If it is bind, it will not affect the new element.
Example:
<ul> <li>第一个子元素<li/> <li>第二个子元素<li/> <li>第三个子元素<li/> </ul>
We want to add click events to all li, you can use on:
$('ul').on('click','li', function () { console.log($(this).text()); });
or bind:
$('ul li').bind('click', function () { console.log($(this).text()); });
Difference:
The first binding with on actually delegates it to the parent ul, that is, the event is only bound to one element
The second one uses the selector to select ul All li elements under are bound to events in turn
If there are many, many sub-elements, the difference will be huge, and bind will seriously affect performance!
If a new li is added at this time:
$('ul').append('<li>第四个子元素<li>');
If it is on bound, this li will also have a click event; if it is bind, there will be no click event.
Related recommendations: js tutorial
The above is the detailed content of What is the difference between bind and on in jquery. For more information, please follow other related articles on the PHP Chinese website!