The usage and difference of delegate and on in jQuery are explained in detail

  • 2020-03-30 01:28:36
  • OfStack

In jQuery1.7,.delegate() has been replaced by.on(). For earlier versions, it still USES the most efficient means of event delegation.
In general, these two methods are equivalent for event binding and for delegates, delegates () and on.

.delegate() adds one or more event handlers to the specified element (which is a child of the selected element) and specifies the function to run when these events occur.

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, [selector], data, handler );

For example: the delegate ()   Code:


On ()   Code:

$("table").on("click", "td", function() {

PS: the difference between the two is that seleter and events are in different order
The delegate and on methods must have a "legal" child of the selected element. Such as

$("table").on("click", "p", function(){...});

It doesn't work because normally table child elements should be tr,td...

On (events,[selector],[data],fn), the argument [selector] is optional,
A selector string is used to filter the descendant of the selector element of the trigger event.
Such as:

$("table").on("click", ".td1", function() {

Filter the table child element with class td1

And the selector for the delegate is required.

Related articles: