Home  >  Article  >  Web Front-end  >  Detailed analysis of the usage and difference between delegate and on in jQuery_jquery

Detailed analysis of the usage and difference between delegate and on in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 17:02:30868browse

In jQuery1.7, .delegate() has been replaced by .on(). As with earlier versions, it still uses the most efficient means of event delegation.
In event binding and delegation, delegate() and on are generally equivalent.

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

Copy code The code is as follows:

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

For example: .delegate() code:
Copy code The code is as follows:

$("table").delegate("td","click",function(){
alert("hello");
});

.on() code:
Copy code The code is as follows:

$("table").on("click", "td", function() {
     alert("hi");
});

PS: Two The difference is that the order of selector and events is different
The child elements of the element selected by the delegate and on methods must be "legal" child elements. For example,
Copy code The code is as follows:

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

will not work, because under normal circumstances, table sub-elements should be tr, td...

on(events,[selector],[data],fn), the parameter [selector] is optional,
a selector string for the descendants of the selector element of the filter that triggers the event.
For example:

Copy code The code is as follows:

$("table"). on("click", ".td1", function() {
alert("hi");
});

Filter table child elements with class td1

The delegate’s selector is required.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn