Home > Web Front-end > JS Tutorial > Example introduction to the usage and difference between delegate and on in jQuery_jquery

Example introduction to the usage and difference between delegate and on in jQuery_jquery

WBOY
Release: 2016-05-16 17:08:01
Original
1015 people have browsed it

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: The difference between the two is that the order of selector and events is different
delegate and on method The child elements of the selected element 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), parameter [selector ] is optional,
A selector string that is used as a descendant of the selector element that triggers the filter event.
For example:
Copy code The code is as follows:

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

Filter table sub-elements with class td1

The delegate’s selector is required.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template